Suppose i have one dictionary menu={'pizza':1,'Burger':1,'sandwitch':0}
when i run tkinter gui these all key will be displayed on GUI. If value is 1 then respected key must be ticked rest will be unticked

Dani AI

Generated

This thread asked by is exactly the kind of UI state-sync problem where checkboxes make sense if multiple items can be selected. 's radiobutton suggestion fits only when a single choice is required; already posted a working example. Below is an alternative that (a) keeps the original dictionary in sync as checkboxes are toggled, (b) avoids the common late-binding lambda bug, and (c) shows a simple way to get a deterministic display order.

import tkinter as tk

menu = {'pizza':1, 'Burger':1, 'sandwitch':0}
root = tk.Tk()

vars_map = {}

def on_toggle(key, var):
    # keep the source dict in sync (0/1)
    menu[key] = 1 if var.get() else 0

for row, (key, value) in enumerate(sorted(menu.items())):
    var = tk.BooleanVar(value=bool(value))
    vars_map[key] = var
    cb = tk.Checkbutton(root, text=key, variable=var,
                        command=lambda k=key, v=var: on_toggle(k, v))
    cb.grid(row=row, sticky='w')

root.mainloop()

Notes and quick troubleshooting:

  • Use sorted(menu.items()) or collections.OrderedDict if you need a stable order across runs. Python dicts preserve insertion order starting with Python 3.7; older interpreters do not.
  • The lambda k=key, v=var: ... pattern captures the current loop variables and avoids every callback referring to the last key.
  • If you want non-0/1 storage, onvalue/offvalue and a StringVar/IntVar work well.
  • To persist user choices, call json.dump(menu, file) inside on_toggle or on app exit.
  • If working on Python 2, import Tkinter (capital T); for modern look use ttk.Checkbutton.

These additions keep the UI and your menu dict synchronized and handle the common pitfalls you might hit when creating widgets programmatically.

Recommended Answers

All 2 Replies

Use radiobuttons instead.

commented: Checks out. +11

python3:

import tkinter as tk
master = tk.Tk()
menu={'pizza':1,'Burger':1,'sandwitch':0}
menuvars={}
for row, (key, value) in enumerate(menu.items()):
    menuvars[key]=tk.IntVar()
    menuvars[key].set(value)
    tk.Checkbutton(master, text=key, variable=menuvars[key]).grid(row=row, sticky=tk.W)
tk.mainloop()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.