Tkinter - 如何在菜单栏中创建子菜单

时间:2013-12-06 16:59:00

标签: python tkinter python-3.3 submenu menubar

有可能吗?通过查看我难倒的选项。在网上搜索并没有把我带到任何地方。我可以在菜单栏中创建子菜单。当我点击File并转到Recent Files时,我指的是做类似于Idle Shell的操作,它会显示一个单独的文件,显示我打开的最近文件。

如果不可能,我必须使用什么才能让它发挥作用?

2 个答案:

答案 0 :(得分:9)

您可以使用add_cascade完全按照向菜单栏添加菜单的方式执行此操作。这是一个例子:

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

答案 1 :(得分:0)

my_menu=Menu(root) # for creating the menu bar
m1=Menu(my_menu,tearoff=0)  # tear0ff=0 will remove the tearoff option ,its default 
value is 1 means True which adds a  tearoff line
m1.add_command(label="Save",command=saveCommand)
m1.add_command(label="Save As",command=saveAsCommand)
m1.add_command(label="Print",command=printCommand)
m1.add_separator()  # this adds a separator line --this is used  keep similar options 
together
m1.add_command(label="Refresh",command=refreshCommand)
m1.add_command(label="Open",command=openCommand)

my_menu.add_cascade(label="File",menu=m1)

m2 = Menu(my_menu)
m2.add_command(label="Copy all",command=copyAllCommand)
m2.add_command(label="Clear all",command=clearAllCommand)
m2.add_command(label="Undo",command=undoCommand)
m2.add_command(label="Redo",command=redoCommand)
m2.add_command(label="Delete",command=deleteCommand)

my_menu.add_cascade(label="Edit",menu=m2)

#all the values in command attribute are functions
my_menu.add_command(label="Exit", command=quit)

root.config(menu=my_menu)

Screenshot of example