Tkinter Checkbuttons 之间的纠缠

Entanglement between Tkinter Checkbuttons

嘿,所以我正在制作一个程序,在主 window 上有一个复选按钮,在顶层 window 上也有一个复选按钮。问题是由于某种原因,顶层复选按钮会影响主复选按钮的状态,或者主复选按钮模仿顶层复选按钮(如果您 check/uncheck 顶层复选按钮,则主复选按钮也 checks/unchecks )。这是显示问题的示例代码:

import tkinter as tk

def toplevel():
    top = tk.Toplevel()
    top.geometry('200x50')

    top_chekbutton = tk.Checkbutton(top, text='top')

    top_chekbutton.pack()

    top.mainloop()

main = tk.Tk()
main.geometry('200x50')

open_top = tk.Button(main, text='open top', command=toplevel)

main_checkbutton = tk.Checkbutton(main, text='main')

main_checkbutton.pack()
open_top.pack()

main.mainloop()

我没有定义状态变量,因为它们似乎不是问题的根源。我在 win10 上使用 python 3.7.7 和 tkinter 8.6。 请帮助:(

作为一般经验法则,Checkbutton 的每个实例都应该有一个与之关联的变量。如果不这样做,将使用对所有 Checkbuttons 都相同的默认值。共享相同变量的所有小部件将显示相同的值。

您可以通过打印出 top_chekbutton.cget("variable")main_checkbutton.cget("variable") 的值来自行验证这一点。在这两种情况下,值都是“!checkbutton”(至少,对于我正在使用的 python 版本)。

因此,为您的复选按钮分配一个变量,例如 BooleanVarIntVarStringVar

main_var = tk.BooleanVar(value=False)
main_checkbutton = tk.Checkbutton(main, text='main')