Home > front end >  Define multiple buttons for Windows commands
Define multiple buttons for Windows commands

Time:01-24

I'm writing a script that will run Windows commands for work ( I will convert it to an executable ). Eventually the script will have 10-15 buttons. How can I make it DRYer?

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)

CodePudding user response:

You could use a dictionary of button titles to functions, then loops over that

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()
  •  Tags:  
  • Related