tkinter Checkbutton widget returning wrong boolean value

萝らか妹 提交于 2019-12-05 18:32:37

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!