Adding Menus and Submenus to the Application


When building a graphical user interface (GUI) application using Python's tkinter library, one important aspect is adding menus and submenus to enhance the application's functionality. Menus provide a convenient way for users to access various features and options within the application. In this article, we will explore how to create menus and submenus using tkinter.

Creating a Basic Menu

To start, let's create a basic menu for our tkinter application. We can do this by following these steps:

  1. Import the tkinter module: import tkinter as tk
  2. Create a new instance of the Tk class, which represents the main window of our application: root = tk.Tk()
  3. Create a menu bar using the Menu class: menu_bar = tk.Menu(root)
  4. Set the menu bar as the main menu of the application: root.config(menu=menu_bar)
  5. Create a menu object using the Menu class and add it to the menu bar: file_menu = tk.Menu(menu_bar)
  6. Add menu items to the menu object: file_menu.add_command(label="Open")

Once these steps are completed, we can display the menu bar by calling the mainloop() method on the root window.

Adding Submenus

To create submenus, we can follow a similar approach as creating a basic menu. However, instead of using the root window as the parent for the menu object, we specify the parent menu as the parent. Let's see how this can be done:

  1. Create a submenu object using the Menu class and specify the parent menu: sub_menu = tk.Menu(file_menu)
  2. Add menu items to the submenu: sub_menu.add_command(label="Option 1")
  3. Add the submenu to the parent menu: file_menu.add_cascade(label="Submenu", menu=sub_menu)

By using the add_cascade() method, we can add submenus to the parent menu, creating a hierarchical structure.

Handling Menu Actions

To handle actions when a menu item is clicked, we can define functions that will be called upon menu item selection. For example:

def open_file():
    # Code to open a file

# ...

file_menu.add_command(label="Open", command=open_file)

In this example, the open_file() function will be executed when the "Open" menu item is clicked.


In this article, we have explored how to add menus and submenus to a tkinter application. By following the provided steps, you can enhance the functionality of your GUI by allowing users to access various options and features conveniently. Additionally, we learned how to handle menu actions by defining corresponding functions. With these techniques, you can create powerful and user-friendly applications using Python's tkinter library.

noob to master © copyleft