为 Windows 命令定义多个按钮

Define multiple buttons for Windows commands

我正在编写一个脚本,它将 运行 Windows 命令用于工作(我会将其转换为可执行文件)。最终脚本将有 10-15 个按钮。我怎样才能让它更干燥?

from tkinter import *
import os, ctypes, sys

os.system('cmd /c "color a"')

root=Tk()
root.title('Common Fixes')
root.geometry("1000x100")

def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

if is_admin():
    button=[]

    def func():
        print("Test line 1 \n Test line 2 \n" )

    def func1():
        os.system('cmd /c "net stop spooler & net start spooler"')

    for i in range(1):
        b = Button(height=2, width=10, text="Help", command=func)
        b.pack()
        button.append(b)

    for i in range(1):
        b = Button(height=2, width=10, text="Two", command=func1)
        b.pack()
        button.append(b)

    root.mainloop()
else:
    # Re-run the program with admin rights
    ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)

您可以使用按钮标题的字典来执行函数,然后循环遍历它

def func():
    print("Test line 1 \n Test line 2 \n" )

def func1():
    os.system('cmd /c "net stop spooler & net start spooler"')

buttons = {
    "Help": func, 
    "Two": func1
}

for title, func in buttons.items():
    b = Button(height=2, width=10, text=title, command=func)
    b.pack()