Tkinter – Command or callback function for Menu item

Set command function for Menu item in Tkinter

To call a command function when a menu item is clicked, pass the callback function name as value for the command parameter when you are adding the menu item to the menu.

For example, consider that we are adding an item Item1 to the menu. We specify a function item_1_action as value for the command parameter.

my_menu.add_command(label="Item1", command=item_1_action)

When user clicks on the menu item Item1, the item_1_action() function is called.

In this tutorial, you will learn how to call a respective callback command function when user clicks on a menu item.

Example

In this example, we shall create a menu with two menu items. When user clicks on the first item Item1, we call item_1_action() callback command function. Similarly, when user clicks on the second item Item2, we call item_2_action() callback command function.

Program

import tkinter as tk

def item_1_action():
    print('You clicked Item1.')

def item_2_action():
    print('You clicked Item2.')

# Create the main window
window = tk.Tk()
window.title("PythonExamples.org")
window.geometry("300x200")

# Create the menu bar
menu_bar = tk.Menu(window)

# Create the menu
menu_1 = tk.Menu(menu_bar, tearoff=0)

# Add items for Menu1
menu_1.add_command(label="Item1", command=item_1_action)
menu_1.add_command(label="Item2", command=item_2_action)

# Add the menu 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

Run on MacOS.

Click on Item1 or Item2.

Summary

In this Python Tkinter tutorial, we learned how to specify a callback command function for a menu item, so that the function executes when user clicks on the menu item, with the help of examples.

Related Tutorials

Privacy Policy Terms of Use

SitemapContact Us