Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Define multiple buttons for Windows commands

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading