我试图让单击按钮中的三个单击按钮在标签上显示一个句子。 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!"
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()
答案 0 :(得分:1)
尽管@martineau的答案有很多好的建议(mainloop(),如何更改标签的文本),但我认为轮询方法不适用于GUI应用程序。
假设用户(通过鼠标/键盘)取消激活了CheckButtons, * ,则您不想要定期检查其状态。定期轮询时,您会遇到两个问题:
处理用户交互的正确方法是指定一个回调,该回调将在CheckButton的状态由于用户操作而改变时执行。 CheckButton为此使用一个command
参数:
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()
* 如果您通过代码更改CheckButton的状态,则只需在更改状态后检查状态即可。
答案 1 :(得分:0)
在GUI Buttons
运行时,您需要定期检查mainloop()
的状态。您可以使用通用窗口小部件after
方法在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()