单击足够多的复选框时,如何设置复选框以在标签中显示单词?

时间:2019-09-14 06:44:32

标签: python python-3.x tkinter

我试图让单击按钮中的三个单击按钮在标签上显示一个句子。 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()

2 个答案:

答案 0 :(得分:1)

尽管@martineau的答案有很多好的建议(mainloop(),如何更改标签的文本),但我认为轮询方法不适用于GUI应用程序。

假设用户(通过鼠标/键盘)取消激活了CheckButtons, * ,则您不想要定期检查其状态。定期轮询时,您会遇到两个问题:

  • 没有对用户操作的立即响应:在最坏的情况下,标签的文本只会在间隔之后更新,即,如果间隔为500ms,则单击复选框后标签可能会更改500ms。
  • 大多数情况下,您的代码虽然没有更改,但并没有必要检查按钮状态

处理用户交互的正确方法是指定一个回调,该回调将在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()