禁用Tkinter中其他复选框的复选框
问题描述:
我正在尝试创建一个小桌面应用程序。在主窗口我有四个复选框,每个复选框具有值变量(1 0为关,对):禁用Tkinter中其他复选框的复选框
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_checkbutton
和randomize_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)
:我写的小功能这一点。我如何实现它,所以这个功能一直在被检查?
答
首先,randomize_cards_checkbutton和所有其他checkbutton变量等于None,因为这是grid()返回的值。对于checkbutton,当状态改变时使用“command =”来调用函数。请注意,您必须获取()Tkinter变量才能将其变成Python变量。任何两个按钮都可用于此测试/示例,但每个checkbutton在最终程序中都会有一个“command =”回调,它将禁用/启用您希望的其他任何checkbutton。至少,使用一些打印语句来帮助您调试。 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()