Python - GUI Programming - Menu Widget
The Menu widget in Python is used to create menus that can be attached to the root window or any other widget. A menu is a group of options that a user can choose from to perform a specific action. The Menu widget can contain commands, radiobuttons, checkboxes, and submenus. In this tutorial, we will learn how to create and use Menus in Python using the Tkinter module.
Creating a Menu:
To create a menu in Tkinter, we first need to create a Menu object. The syntax for creating a Menu object is as follows:
menu = Menu(master)
Here, the master parameter specifies the widget that the menu will be attached to.
Adding Items to a Menu:
After creating the Menu object, we can add items to it using the add() method. The syntax for adding an item to a Menu is as follows:
menu.add(type, options)
Here, type specifies the type of item to be added, and options specifies the options for the item. The types of items that can be added to a Menu are:
- "command" : Adds a command item to the menu
- "radiobutton" : Adds a radiobutton item to the menu
- "checkbutton" : Adds a checkbutton item to the menu
- "cascade" : Adds a submenu to the menu
Example:
from tkinter import *
def do_nothing():
filewin = Toplevel(root)
button = Button(filewin, text="Do nothing button")
button.pack()
root = Tk()
menu = Menu(root)
root.config(menu=menu)
file_menu = Menu(menu)
menu.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="New", command=do_nothing)
file_menu.add_command(label="Open", command=do_nothing)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=root.quit)
edit_menu = Menu(menu)
menu.add_cascade(label="Edit", menu=edit_menu)
edit_menu.add_command(label="Cut", command=do_nothing)
edit_menu.add_command(label="Copy", command=do_nothing)
edit_menu.add_command(label="Paste", command=do_nothing)
help_menu = Menu(menu)
menu.add_cascade(label="Help", menu=help_menu)
help_menu.add_command(label="About", command=do_nothing)
root.mainloop()
In the above example, we first create a root window using the Tk() method. We then create a Menu object menu and attach it to the root window using the config() method. We then create three submenu objects file_menu, edit_menu, and help_menu using the Menu() method and add them to the menu using the add_cascade() method. We then add command items to each submenu using the add_command() method.
Handling Menu Events:
To handle the events generated by the Menu widget, we need to attach a command to the item using the command parameter of the add_command() method. The command attached to the item will be called whenever the user selects that item from the menu.
In the above example, we have attached the do_nothing() function to each command item. This function opens a new Toplevel window with a button that does nothing.