Tkinter - How to create submenus in menubar
Asked Answered
V

2

6

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?

Valgus answered 6/12, 2013 at 16:59 Comment(0)
D
19

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()
Ditmore answered 6/12, 2013 at 18:31 Comment(3)
Thanks. It works but how do I get rid of -------- break above both the main menu and the submenu.Valgus
use the option tearoff=FalseDitmore
I had seen that on a youtube video series a couple of days ago and didn't realize the ------- were tearoff related. I just saw the answer thanks to do some more research. Thanks for the help.Valgus
O
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

Oriole answered 27/8, 2020 at 17:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.