0

enter image description here

How to do this without writing separate function for each check box as i have done in the code commented out, what is wrong with the "func" function why doesn't it work?

from tkinter import *

ws = Tk()
ws.title('Terminator')
ws.geometry('200x80')


# def vlc_func():
#     if vlc.get() == 1:
#         print("selected")
#     elif vlc.get() == 0:
#         print("deselected")

# def notepad_func():
#     if notepad.get() == 1:
#         print("selected")
#     elif notepad.get() == 0:
#         print("deselected")

def func(associated_variable):
    if associated_variable.get() == 1:
        print("selected")
    elif associated_variable.get() == 0:
        print("deselected")


vlc = IntVar()
vlc.set(0)
Checkbutton(ws, text= "vlc.exe", variable=vlc, onvalue=1, offvalue=0, command= func(vlc)).pack()

notepad = IntVar()
Checkbutton(ws, text= "notepad.exe", variable=notepad, onvalue=1, offvalue=0, command= func(notepad)).pack()




ws.mainloop()

    
  • 1
    You are almost near! You need to put ```lambda: func(notepad)```, ```lambda:``` when you pass an argument –  Jul 04 '21 at 05:27

1 Answers1

0

The issue is with the way you pass arguments to your callback functions. If you pass the argument directly when you set the command parameter, the function is called and run once, and only the result of the function is passed, not the function itself. That's what leads to the behavior "deselected" printed twice when you run your script

Check this: How to pass an argument to event handler in tkinter\ Once you follow this, everything should work as your expect

Emmanuel Murairi
  • 321
  • 2
  • 15