tkinter Checkbutton widget returning wrong boolean value
The boolean value is changed after the bind callback is made. To give you an example, check this out:
from tkinter import *def getBool(event): print(boolvar.get())root = Tk()boolvar = BooleanVar()boolvar.set(False)boolvar.trace('w', lambda *_: print("The value was changed"))cb = Checkbutton(root, text = "Check Me", variable = boolvar)cb.bind("<Button-1>", getBool)cb.pack()root.mainloop()
When you presses the Checkbutton, the first output is False
then it's "The value was changed"
, which means that the value was changed after the getBool
callback is completed.
What you should do is to use the command
argument for the setting the callback, look:
from tkinter import *def getBool(): # get rid of the event argument print(boolvar.get())root = Tk()boolvar = BooleanVar()boolvar.set(False)boolvar.trace('w', lambda *_: print("The value was changed"))cb = Checkbutton(root, text = "Check Me", variable = boolvar, command = getBool)cb.pack()root.mainloop()
The output is first "The value was changed"
then True
.
For my examples, I used boolvar.trace
, it runs the lambda callback when the boolean value changes ('w'
)