Create Submenus in Tkinter
To create submenus in Tkinter, create a submenu using Tk.Menu class, and cascade it to a menu using Menu.add_cascade() method.
A submenu is also a Menu object just like another menu, but to which menu we cascade the submenu makes the difference of how it is displayed in the UI.
For example, consider the following code snippet which shows the hierarchy of the menus. The items are ignored for explanation purpose.
# Menu bar
menu_bar = tk.Menu(window)
# A menu in Menu bar
menu_1 = tk.Menu(menu_bar, tearoff=0)
# A submenu in a menu
submenu_1 = tk.Menu(menu_1, tearoff=0)
# Add submenu to the menu
menu_1.add_cascade(label="Submenu1", menu=submenu_1)
# Add menu to the menu bar
menu_bar.add_cascade(label="Menu1", menu=menu_1)
- menu_bar is the master of menu_1.
- menu_1 is the master of submenu_1.
In this tutorial, you will learn how to create a submenu in a Menu in Tkinter, as shown in the following example menu.
Menu1 # Menu1 is a menu in menu bar
Item1 # item under Menu1
Item2 # item under Menu1
SubMenu1 # submenu under Menu1
Item3 # item under SubMenu1
Item4 # item under SubMenu1
Item5 # item under SubMenu1
Example
In this example, we shall create a window, create a menu bar, create a menu, say Menu1, then create a submenu Submenu1 under Menu1.
Python Program
import tkinter as tk
# Create the main window
window = tk.Tk()
# Create the menu bar
menu_bar = tk.Menu(window)
# Create a menu "Menu1" in menu bar
menu_1 = tk.Menu(menu_bar, tearoff=0)
# Create Submenu
submenu_1 = tk.Menu(menu_1, tearoff=0)
# Add items to Submenu
submenu_1.add_command(label="Item3")
submenu_1.add_command(label="Item4")
submenu_1.add_command(label="Item5")
# Add items to Menu1
menu_1.add_command(label="Item1")
menu_1.add_command(label="Item2")
menu_1.add_cascade(label="SubMenu1", menu=submenu_1)
# Add the menu "Menu1" to the menu bar
menu_bar.add_cascade(label="Menu1", menu=menu_1)
# Attach the menu bar to the main window
window.config(menu=menu_bar)
# Start the Tkinter event loop
window.mainloop()
Output
Summary
In this Python Tkinter tutorial, we learned how to create Submenus in Tkinter, with the help of examples.