![](/img/trans.png)
[英]my python code doesn't get executed. No error, no process finished text just blank. Other codes works fine
[英]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。
我尝试过的事情:
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.