Tkinter - How to create submenus in menubar

我是研究僧i 提交于 2021-02-19 01:56:08

问题


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?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/20429448/tkinter-how-to-create-submenus-in-menubar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!