#!python # -*- mode: python; Encoding: utf-8; coding: utf-8 -*- # Last updated: <2022/12/06 06:43:27 +0900> """ Test tkinter.Checkbutton Windows10 x64 22H2 + Python 3.9.13 64bit """ import tkinter as tk from functools import partial CHK_LIST = [ ["Apple", True], ["Orange", True], ["Lemon", False], ["Peach", False], ["Banana", True], ["strawberry", True], ] def click_cb(n): """Click Checkbutton.""" global cbs, cb_values, msg name = cbs[n].cget("text") value = cb_values[n].get() msg.set(f"{name} (id={n}) is {value}") def click_button(): """Toggle Checkbuttons value.""" global cb_values for cb in cb_values: if True: v = cb.get() cb.set(not v) else: cb.toggle() root = tk.Tk() root.title("Test Checkbutton") root.geometry("400x400") # create Label msg = tk.StringVar(value="Message") lbl = tk.Label(root, textvariable=msg, borderwidth=2, relief="ridge", font=("Arial", "18", "normal")) # create Button button = tk.Button(root, text="Toggle", command=click_button) # create Checkbuttons cb_values = [] cbs = [] for i, d in enumerate(CHK_LIST): def_text, def_value = d # reserve Checkbutton value cb_values.append(tk.BooleanVar(value=def_value)) # create Checkbutton cb = tk.Checkbutton(root, text=def_text, variable=cb_values[i], command=lambda i=i: click_cb(i), # command = partial(click_cb, i), # command = click_cb(i), # command = lambda: click_cb(i), ) cbs.append(cb) cbs[i].pack() lbl.pack() button.pack() root.mainloop()