In Tkinter (Python) I try to dynamically uncheck a CheckBox when an another CheckBox is checked but the behavior is rather erratic.
- If the first box is checked and i check the second one: the second box checks for few seconds then it unchecks. The event related to the second CheckBox doesn't trigger.
- If the second box is checked and i check the first one: the behavior is correct as it uncheck the second one and check the first one. The event related to the first CheckBox does trigger.
- If there's no single box checked and I check one box at the time the events do trigger normally.
My code :
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()
Any ideas of why this functiontoggle_entries
doesn't work properly?