Skip to content
Advertisement

Generating a menu for a tkinter window doesn’t work using a function but works just fine if the steps are executed on a python console

I’m trying to generate a set of menus for a program from a dictionary using a more complex version of the function build_menu below. The function detects what it is supposed to do correctly (detects the structure of submenus and menu entries as desired) but it fails to add them to the window.

Things I have tried:

  • running the code step by step in a python console – works as intended
  • storing the menu objects in a global list so they don’t go out of scope in case they get garbage collected – didn’t work

What am I missing?

import tkinter as tk

def not_implemented():
    pass

def build_menu(structure_dict, menu):
    for entry in structure_dict:
        if isinstance(structure_dict[entry], dict):
            submenu = tk.Menu(menu, tearoff=False)
            build_menu(structure_dict[entry], submenu)
            menu.add_cascade(label=entry, menu=submenu)
        if callable(structure_dict[entry]):
            menu.add_command(label=entry, command=structure_dict[entry])

# format:
#   "":{} -> menu or submenu
#   "":function -> menu entry
menu_structure = {
   "Help": {
        "Manual...": not_implemented,
        "About...": not_implemented,
    }
}

main_window = tk.Tk()

menubar = tk.Menu(main_window)
menubar = build_menu(menu_structure, menubar)
main_window.config(menu=menubar)

main_window.mainloop()

Advertisement

Answer

Turns out I am an idiot. I accidentally assigned build_menu to the variable holding the menu bar.

Correct code near the end is this:

menubar = tk.Menu(main_window)
build_menu(menu_structure, menubar)
main_window.config(menu=menubar)

main_window.mainloop()
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement