tkinter
  1. tkinter-menu

Menu - Tkinter Menu Widgets

A Menu in Tkinter is a dropdown list of options or commands. It is used to provide a set of options to the user. The Menu widget in Tkinter provides a menu bar that consists of various menu items, and each menu item may have sub-items (or sub-menus).

Syntax

The basic syntax for creating a Menu widget in Tkinter is as follows:

menu_widget = Menu(parent, **options)

Here, parent is the Tkinter widget on which the menu bar will appear, and options are the configuration options for the menu bar.

Example

Consider the following example, where a Menu widget is created and attached to the root window:

import tkinter as tk

root = tk.Tk()

# create a menu bar
menu_bar = tk.Menu(root)

# create a file menu
file_menu = tk.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="New")
file_menu.add_command(label="Open")
file_menu.add_separator()
file_menu.add_command(label="Exit", command=root.quit)

# add file menu to menu bar
menu_bar.add_cascade(label="File", menu=file_menu)

# display the menu bar
root.config(menu=menu_bar)

# run the window
root.mainloop()

In this example, a menu bar is created using tk.Menu(), and options are added to the menu bar using add_command() and add_separator() methods. The file menu is then added to the menu bar using add_cascade(), and the menu bar is displayed on the root window using root.config(menu=menu_bar).

Output

The output of the above code will be a window with a menu bar containing a file menu. The user can click on the file menu to see a dropdown list of options.

Explanation

The Menu widget in Tkinter provides a menu bar that consists of various menu items. Each menu item may have sub-items (or sub-menus). These sub-menus can have their own menu items or sub-menus.

In the above example code, a menu bar is created using tk.Menu(), and sub-menus are added to the menu bar using the add_cascade() method. Menu items are added to these sub-menus using the add_command() method.

Use

The Menu widget in Tkinter is used to provide a dropdown list of options or commands to the user. It is commonly used in applications that require the user to select from a set of options or commands, such as file explorers, text editors, and image editors.

Important Points

  • A Menu widget can be created using the tk.Menu() constructor.
  • Menu options can be added to a Menu widget using the add_command() and add_separator() methods.
  • Sub-menus can be created using the Menu constructor and added to a menu using the add_cascade() method.
  • The post() method of a Menu widget can be used to display a menu at a specific location.

Summary

The Menu widget in Tkinter provides a dropdown list of options or commands to the user. It is commonly used in applications that require the user to select from a set of options or commands. Menu options and sub-menus can be created using the add_command(), add_separator(), and add_cascade() methods.

Published on: