Tkinter - How to create submenus in menubar

confused picture confused · Dec 6, 2013 · Viewed 13.5k times · Source

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?

Answer

Bryan Oakley picture Bryan Oakley · Dec 6, 2013

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