Tkinter - How to create submenus in menubar Tkinter - How to create submenus in menubar tkinter tkinter

Tkinter - How to create submenus in menubar


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 nametry:    import Tkinter as tk# Fall back to Python 3 if import failsexcept ImportError:    import tkinter as tkclass 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()


my_menu=Menu(root) # for creating the menu barm1=Menu(my_menu,tearoff=0)  # tear0ff=0 will remove the tearoff option ,its default value is 1 means True which adds a  tearoff linem1.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 togetherm1.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 functionsmy_menu.add_command(label="Exit", command=quit)root.config(menu=my_menu)

Screenshot of example