Tkinter run multiple functions by checking the Checkbuttons

1.4k views Asked by At

I'm building a script to make a GUI window presenting some functions I made before.

I would like to tick the buttons which I want to run the functions. So far I can run a function by checking the checkbox. But only one.

button1 = ttk.Checkbutton(window,
    command = function1
    )

But I have several check buttons and at the end 'Run' button to run the all functions checked above.

button1 = ttk.Checkbutton(window,
    )
button2 = ttk.Checkbutton(window,
    )
button3 = ttk.Checkbutton(window,
    )

run_button = ttk.Button(window,
    text = 'run',
    command = proper command to run the functions ticked above
    )

Is there any way to make it possible?

  • And plus I would like to close the GUI window once I hit the run button, but couldn't find a solution yet.

Thanks in advance!!

1

There are 1 answers

1
Karthik On BEST ANSWER

Please check this snippet that performs hardcoded add,subtract,multiply,delete functions.

  1. As you tick the checkbox the respective function is triggered.
  2. As you click the run button, all the functions will be triggered.
  3. After clicking run button the output will be printed as well as the tkinter window will be closed.
from tkinter import *
master = Tk()

def run_all():
    var1.set(1)
    var2.set(1)
    var3.set(1)
    var4.set(1)
    ad()
    sub()
    mul()
    div()
    master.destroy()

def ad():
    if(var1.get()==1):
        print(5+5)
def sub():
    if(var2.get()==1):
        print(5-5)
def mul():
    if(var3.get()==1):
        print(5*5)
def div():
    if(var4.get()==1):
        print(5/5)
Label(master, text="Operations:").grid(row=0, sticky=W)
var1 = IntVar()
Checkbutton(master, text="Add", variable=var1,command=ad).grid(row=1, sticky=W)
var2 = IntVar()
Checkbutton(master, text="Subtract", variable=var2,command=sub).grid(row=2, sticky=W)
var3 = IntVar()
Checkbutton(master, text="Multiply", variable=var3,command=mul).grid(row=3, sticky=W)
var4 = IntVar()
Checkbutton(master, text="Divide", variable=var4,command=div).grid(row=4, sticky=W)
Button(master, text='Run', command=run_all).grid(row=5, sticky=W, pady=4)
mainloop()

Edit: Based on the comment, now all functions will run only when you press the run button

Label(master, text="Operations:").grid(row=0, sticky=W)
var1 = IntVar()
Checkbutton(master, text="Add", variable=var1).grid(row=1, sticky=W)
var2 = IntVar()
Checkbutton(master, text="Subtract", variable=var2).grid(row=2, sticky=W)
var3 = IntVar()
Checkbutton(master, text="Multiply", variable=var3).grid(row=3, sticky=W)
var4 = IntVar()
Checkbutton(master, text="Divide", variable=var4).grid(row=4, sticky=W)
Button(master, text='Run', command=run_all).grid(row=5, sticky=W, pady=4)
mainloop()