Python 如何设置checkbuttons以在单击足够多的checkbuttons时在标签中显示单词?
我试图让选中按钮在单击三个选中按钮时在标签上显示一个句子。 对于特金特来说,这是我迄今为止尝试过的Python 如何设置checkbuttons以在单击足够多的checkbuttons时在标签中显示单词?,python,python-3.x,tkinter,Python,Python 3.x,Tkinter,我试图让选中按钮在单击三个选中按钮时在标签上显示一个句子。 对于特金特来说,这是我迄今为止尝试过的 from tkinter import * root = Tk() Check_button_one = IntVar() Check_button_two = IntVar() Check_button_three = IntVar() Checkbutton(root, variable = Check_button_one).pack() Checkbutton(root, varia
from tkinter import *
root = Tk()
Check_button_one = IntVar()
Check_button_two = IntVar()
Check_button_three = IntVar()
Checkbutton(root, variable = Check_button_one).pack()
Checkbutton(root, variable = Check_button_two).pack()
Checkbutton(root, variable = Check_button_three).pack()
default_text = ""
updated_text = "what a legend you are!"
while Check_button_one == 1 and Check_button_two == 1 and Check_button_three == 1:
default_text = updated_text
Label_main = Label(root, text = default_text)
Label_main.pack()
当GUI mainloop运行时,您需要定期检查按钮的状态。您可以在tkinter应用程序中使用通用小部件方法来实现这一点 例如:
from tkinter import *
root = Tk()
Check_button_one = IntVar()
Check_button_two = IntVar()
Check_button_three = IntVar()
Checkbutton(root, variable = Check_button_one).pack()
Checkbutton(root, variable = Check_button_two).pack()
Checkbutton(root, variable = Check_button_three).pack()
default_text = ""
updated_text = "what a legend you are!"
Label_main = Label(root, text=default_text)
Label_main.pack()
def check_buttons():
if Check_button_one.get() and Check_button_two.get() and Check_button_three.get():
Label_main.config(text=updated_text)
else: # Make sure the default is displayed.
Label_main.config(text=default_text)
root.after(500, check_buttons) # Schedule next check in 500 msecs
check_buttons() # Start polling buttons.
root.mainloop()
尽管@martineau的answermainloop中有很多很好的建议,比如如何更改标签的文本,但我认为轮询方法不适合GUI应用程序 假设用户通过鼠标/键盘*停用复选按钮,则不希望定期检查其状态。在间隔轮询时,存在两个问题: 没有对用户操作的即时响应:在最坏的情况下,标签的文本只会在间隔后更新,即如果间隔为500毫秒,则标签可能会在单击checkbutton后500毫秒更改。 大多数情况下,您的代码并不需要检查按钮状态,尽管它们没有改变 处理用户交互的正确方法是指定一个回调,该回调在用户操作导致CheckButton的状态发生更改时执行。CheckButton为此目的使用命令参数:
from tkinter import *
root = Tk()
Check_button_one = IntVar()
Check_button_two = IntVar()
Check_button_three = IntVar()
default_text = ""
updated_text = "what a legend you are!"
Label_main = Label(root, text = default_text)
Label_main.pack()
def checkbuttonCallback():
if Check_button_one.get() and Check_button_two.get() and Check_button_three.get():
Label_main.config(text=updated_text)
else:
Label_main.config(text=default_text)
Checkbutton(root, variable = Check_button_one, command=checkbuttonCallback).pack()
Checkbutton(root, variable = Check_button_two, command=checkbuttonCallback).pack()
Checkbutton(root, variable = Check_button_three, command=checkbuttonCallback).pack()
root.mainloop()
*如果通过代码更改CheckButtons的状态,只需在更改后检查状态即可