使用tkinter编程时,我发现Checkbutton小部件的行为非常奇怪。我用下面的代码重新创建了错误:
import tkinter
from tkinter import *
def displayWelcomeScreen(root):
root2 = Toplevel(root)
root2.geometry('600x380')
root2.focus_set()
Checked = IntVar()
CheckButton1 = Checkbutton(root2, variable=Checked)
CheckButton1.place(relx=0.5, rely=0.5, anchor=CENTER)
CheckButton1.select()
# Create a dummy button that makes the Checkbutton appear checked to the user
#Button(root2, command= lambda event: Checked.get())
root = Tk()
root.geometry('700x400')
displayWelcomeScreen(root)
root.mainloop()
当使用Toplevel(root)
创建一个新窗口时,我在其中放置了一个Checkbutton,即使我使用了.select()
方法,用户也不会觉得它是选中的
然而,当我创建一个伪按钮时,它的命令提到了与我的Checkbutton关联的IntVar,不知何故,它被初始化为checked正确。这几乎就像编译器检查Checkbutton是否有用,并根据它决定是否将其显示为选中状态
编辑:Checkbutton肯定是在引擎盖下被选中的,因为如果我在CheckButton1.select()
命令之前和之后运行print(Checked.get())
,值就会改变,用户不会看到它
有人知道为什么会这样吗
编辑2:多亏了jasonharper的解释,我添加了行CheckButton1.intvar = Checked
,它在不需要虚拟按钮的情况下工作。当函数超出范围时,选中的变量丢失,因此Checkbutton无处存储其状态,因此我们需要保留对它的引用,以便它不会消失
目前没有回答
相关问题 更多 >
编程相关推荐