I have a simple GUI here that's suppose to return a boolean value depending on whether the check button is checked or not. I've set the boolean variable to False hence the empty check button. What I don't understand is that when I check the button, the function binded to that widget returns a False instead of True. Why is that?
Here's the code...
from tkinter import *
from tkinter import ttk
def getBool(event):
print(boolvar.get())
root = Tk()
boolvar = BooleanVar()
boolvar.set(False)
cb = Checkbutton(root, text = "Check Me", variable = boolvar)
cb.bind("<Button-1>", getBool)
cb.pack()
root.mainloop()
when checking the empty button the function outputs...
False
Shouldn't it return True
now that the button is checked?
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'
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With