简体   繁体   中英

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()

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM