The Python Oracle

tkinter Checkbutton widget returning wrong boolean value

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3

--

Chapters
00:00 Tkinter Checkbutton Widget Returning Wrong Boolean Value
00:39 Accepted Answer Score 6
01:30 Thank you

--

Full question
https://stackoverflow.com/questions/4397...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #tkinter #python35

#avk47



ACCEPTED ANSWER

Score 6


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')