繁体   English   中英

使用 function 无法为 tkinter window 生成菜单,但如果在 python 控制台上执行这些步骤,则工作正常

[英]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

我正在尝试使用下面 function build_menu的更复杂版本从字典中为程序生成一组菜单。 function 检测到它应该正确执行的操作(根据需要检测子菜单和菜单条目的结构)但它无法将它们添加到 window。

我尝试过的事情:

  • 在 python 控制台中逐步运行代码 - 按预期工作
  • 将菜单对象存储在global列表中,这样它们就不会 scope 中的 go 以防它们被垃圾收集 - 没有用

我错过了什么?

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

原来我是个白痴。 我不小心将build_menu分配给了保存菜单栏的变量。

接近尾声的正确代码是这样的:

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

main_window.mainloop()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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