提问人:Tolga 提问时间:11/4/2023 更新时间:11/4/2023 访问量:26
菜单中的 Tkinter 菜单
Tkinter Menu within menu
问:
我有一个编写 tkinter 的应用程序,并在菜单中创建了菜单来选择书籍类别
问题是我无法编写具有子类别的类别名称。如果没有子类别,则在按钮上成功写入类别名称
它在 macOS 中完全按照我的意愿工作,但在 Windows 中不起作用
我从json文件中获取分类,文件结构如下图作为示例;
{
"Book": {
"ID": 1,
"SubCategory": {
"Law Books": {
"ID": 10
}
"Computer Science Books": {
"ID": 20,
"SubCategory": {
"Programming": {
"ID": 30
}
}
}
}
}
}
self.category_button = ttk.Menubutton(self, text='Choose')
self.category_button = self.create_categories_menu(self.category_button)
def create_categories_menu(self, category_button):
categories = helper.load_categories()
top_menu = tk.Menu(category_button, tearoff=False)
category_button.configure(menu=top_menu)
self.create_sub_category(categories, category_button, top_menu)
return category_button
def create_sub_category(self, categories, category_button, top_menu):
# create submenus as find subcategories
for category in categories:
if ('SubCategory' not in categories[category]):
top_menu.add_cascade(
label=category,
command=lambda c=category:
self.set_button_label(category_button, c))
else:
new_menu = tk.Menu(top_menu, tearoff=False)
top_menu.add_cascade(
label=category,
menu=new_menu,
command=lambda c=category:
self.set_button_label(category_button, c))
self.create_sub_category(
categories[category]['SubCategory'],
category_button,
new_menu)
def set_button_label(self, button, name):
button['text'] = name
答: 暂无答案
评论