tkinter Checkbutton 小部件返回错误的布尔值 [英] tkinter Checkbutton widget returning wrong boolean value
问题描述
我这里有一个简单的 GUI,它假设根据检查按钮是否被选中来返回一个布尔值.我已将布尔变量设置为 False 因此空检查按钮.我不明白的是,当我检查按钮时,绑定到该小部件的函数返回 False 而不是 True.这是为什么?
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?
这是代码...
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
既然选中了按钮,它不应该返回 True
吗?
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()
当你按下 Checkbutton 时,第一个输出是 False
然后是 "The value was changed"
,这意味着在 getBool 之后值被改变了
回调完成.
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.
你应该做的是使用 command
参数来设置回调,看:
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()
输出首先是值已更改"
,然后是True
.
在我的例子中,我使用了 boolvar.trace
,它在布尔值改变时运行 lambda 回调 ('w'
)
For my examples, I used boolvar.trace
, it runs the lambda callback when the boolean value changes ('w'
)
这篇关于tkinter Checkbutton 小部件返回错误的布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!