我正试着用Tkinder创建一个菜单.此菜单由多个子菜单组成.
我用for循环构建了一个 struct 来形成这些菜单.
但是,我无法使菜单按钮根据 Select 进行更新
示例代码:
import tkinter as tk
from tkinter import ttk
class Window:
def __init__(self, master):
self.categories = {
"A": {
"B": {
"C": {},
"D": {},
},
"E": {
"F": {}
}
},
"G": {}
}
self.menu_button = ttk.Menubutton(master, text = "Select")
self.top_menu = tk.Menu(self.menu_button, tearoff = False)
self.menu_button.configure(menu = self.top_menu)
self.create_category_menu(self.categories, self.top_menu)
self.menu_button.pack()
# I created a recursive function, constantly checking subcategories
def create_category_menu(self, categories, top_menu):
for category in categories:
if (len(categories[category]) == 0):
# if the category has no subcategories, just add the name
top_menu.add_cascade(label = category)
else:
# If there are subcategories, create a separate menu for subcategories
# and insert it into the top menu
menu = tk.Menu(top_menu)
top_menu.add_cascade(label = category, menu = menu)
self.create_category_menu(categories[category], menu)
root = tk.Tk()
window = Window(root)
root.mainloop()
代码按我想要的方式创建菜单,但我无法将所选选项写入按钮
top_menu.add_cascade(label = category, command = self.func(category))
top_menu.add_cascade(label = category, menu = menu, command = self.func(category))
我像这样更改了这两行,还在代码中创建了以下函数;
def func(self, category):
self.menu_button["text"] = category
这一次,它将类别词典的底值("G")写入按钮.
共有97个嵌套类别.上面的代码是我为这个问题准备的示例