Tkinter - 如何在菜单栏中创建子菜单
问题描述:
有可能吗?通过查看选项,我很难过.在网上搜索并没有带我去任何地方.我可以在菜单栏中创建子菜单吗?我指的是当我单击文件"并转到最近的文件"时执行类似于 Idle Shell 的操作,它会拉出一个单独的文件,显示我最近打开的文件.
Is it possible? By looking at the options I'm stumped. Searching on the web hasn't lead me anywhere. Can I create a submenu in the menubar. I'm referring to doing something similar to Idle Shell when I click on File and go down to Recent Files and it pulls up a separate file showing the recent files I've opened.
如果不可能,我必须用什么来让它工作?
If it's not possible what do I have to use to get it to work?
答
使用 add_cascade
完全按照向菜单栏添加菜单的方式进行操作.举个例子:
You do it exactly the way you add a menu to the menubar, with add_cascade
. Here's an example:
# Try to import Python 2 name
try:
import Tkinter as tk
# Fall back to Python 3 if import fails
except ImportError:
import tkinter as tk
class Example(tk.Frame):
def __init__(self, root):
tk.Frame.__init__(self, root)
menubar = tk.Menu(self)
fileMenu = tk.Menu(self)
recentMenu = tk.Menu(self)
menubar.add_cascade(label="File", menu=fileMenu)
fileMenu.add_cascade(label="Open Recent", menu=recentMenu)
for name in ("file1.txt", "file2.txt", "file3.txt"):
recentMenu.add_command(label=name)
root.configure(menu=menubar)
root.geometry("200x200")
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()