【问题标题】:Define multiple buttons for Windows commands为 Windows 命令定义多个按钮
【发布时间】:2022-01-24 04:14:24
【问题描述】:

我正在编写一个运行 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)

【问题讨论】:

    标签: python tkinter dry


    【解决方案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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-08
      • 2012-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-09
      • 2017-06-19
      • 1970-01-01
      相关资源
      最近更新 更多