禁用Tkinter中其他复选框的复选框

时间:2014-12-08 01:08:12

标签: python-2.7 checkbox tkinter

我试图创建一个小桌面应用程序。在主窗口中,我有四个复选框,每个复选框都有变量值(0表示关闭,1表示打开):

random_cards = IntVar() 
random_stacks = IntVar() 
flip_cards = IntVar() 
wildcard = IntVar()

randomize_cards_checkbutton = Checkbutton(text="Randomize cards", variable=random_cards).grid(row=0, column=0, in_=options, sticky=W)
randomize_stacks_checkbutton = Checkbutton(text="Randomize stacks", variable=random_stacks).grid(row=1, column=0,in_=options, sticky=W)
wildcard_checkbutton = Checkbutton(text="Wildcard", variable=wildcard).grid(row=2, column=0, in_=options, sticky=W)
flip_cards_checkbutton = Checkbutton(text="Flip cards", variable=flip_cards).grid(row=3, column=0, in_=options, sticky=W)

我希望行为是,如果启用了wildcard_checkbutton,则会禁用两个复选框randomize_cards_checkbuttonrandomize_stacks_checkbutton(灰色),反之亦然。我为此写了一些小功能:

def check_checkbuttons(random_cards, random_stacks, wildcard):
    if wildcard == 1:
        randomize_cards_checkbutton.configure(state=DISABLED)
        randomize_stacks_checkbutton.configure(state=DISABLED)
    elif random_cards == 1 or random_stacks == 1:
        wildcard_checkbutton.configure(state=DISABLED)

现在我不知道如何让这个功能一直运行"所有时间"。如何实现它以便始终检查此功能?

1 个答案:

答案 0 :(得分:1)

首先,randomize_cards_checkbutton和所有其他checkbutton变量等于None,因为这就是grid()返回的内容。对于checkbutton,使用“command =”在状态更改时调用该函数。请注意,您必须获取()Tkinter变量以将其转换为Python变量。并且任何两个按钮都适用于此测试/示例,但每个checkbutton将在最终程序中具有“command =”回调,该回调将禁用/启用您想要的其他按钮。至少,使用一些打印语句来帮助您进行调试。 print语句会告诉你什么是None,而且通配符是PY_VAR,而不是整数等。

def cb_check():
    if random_cards.get():
        randomize_stacks_checkbutton.config(state=DISABLED)
    else:
        randomize_stacks_checkbutton.config(state=NORMAL)

top=Tk()
random_cards = IntVar() 
random_stacks = IntVar() 
flip_cards = IntVar() 
wildcard = IntVar()

randomize_cards_checkbutton = Checkbutton(top, text="Randomize cards",
                              variable=random_cards, command=cb_check)
randomize_cards_checkbutton.grid(row=0, column=0, sticky=W)

randomize_stacks_checkbutton = Checkbutton(top, text="Randomize stacks",
                               variable=random_stacks, bg="lightblue",
                               disabledforeground="gray")
randomize_stacks_checkbutton.grid(row=1, column=0, sticky=W)

top.mainloop()
相关问题