在 Tkinter (Python) 中,当选中另一个复选框时,我尝试动态取消选中一个复选框,但行为相当不稳定。
我的代码:
import tkinter as tk
class App(tk.Tk):
def __init__(self):
super().__init__()
self.frame = tk.Frame(self)
self.frame.pack(fill=tk.BOTH, expand=True)
self.entry1 = tk.Canvas(self.frame, width=100, height=100, highlightthickness=0, bd=0, bg="green", relief='solid')
self.entry1.grid(row=0, column=0)
self.entry2 = tk.Canvas(self.frame, width=100, height=100, highlightthickness=0, bd=0, bg="red", relief='solid')
self.check_var1 = tk.BooleanVar()
self.check_var1.set(True)
self.check_box1 = tk.Checkbutton(self, text="Show Green", variable=self.check_var1, command=lambda: self.toggle_entries(self.check_var1))
self.check_box1.pack()
self.check_var2 = tk.BooleanVar()
self.check_box2 = tk.Checkbutton(self, text="Show Red", variable=self.check_var2, command=lambda: self.toggle_entries(self.check_var2))
self.check_box2.pack()
self.check_var1.trace_add('write', self.check_var_changed)
self.check_var2.trace_add('write', self.check_var_changed)
self.toggle_entries(self.check_var1)
def toggle_entries(self, var):
if var is self.check_var1:
if var.get():
self.entry1.grid()
self.entry2.grid_remove()
self.check_var2.set(False)
elif var is self.check_var2:
if var.get():
self.entry2.grid()
self.entry1.grid_remove()
self.check_var1.set(False)
def check_var_changed(self, *args):
if self.check_var1.get():
self.check_var2.set(False)
elif self.check_var2.get():
self.check_var1.set(False)
if __name__ == "__main__":
app = App()
app.mainloop()
你知道为什么这个功能
toggle_entries
无法正常工作吗?
解决了。问题是
check_var_changed
:
def check_var_changed(self, *args):
if self.check_var1.get():
self.check_var2.set(False)
elif self.check_var2.get():
self.check_var1.set(False)
干扰
toggle_entries
函数创建循环。我删除了 check_var_changed
以及
self.check_var1.trace_add('write', self.check_var_changed)
self.check_var2.trace_add('write', self.check_var_changed)
现在效果很好。我保留这篇文章以防有人遇到同样的问题。