Tkinter – Add Keyboard Shortcut to Menu item

Add keyboard shortcut to Menu item in Tkinter

To add a keyboard shortcut to a menu item in Tkinter, pass the keyboard shortcut as value for the accelerator parameter in the while adding the item to the menu using add_command(), add_cascade(), etc.

For example, if you would like to set the “Ctrl+A” as keyboard shortcut for a menu item, then use the following syntax when you are adding the command menu item to the menu.

menu_1.add_command(label="Item1", accelerator="Ctrl+A")

In this tutorial, you will learn how to add or specify a keyboard shortcut to a menu item in Tkinter, as shown in the following example menu.

Menu1               # Menu1 is a menu in menu bar
  Item1    Ctrl+A     # item under Menu1 with keyboard shortcut
  Item2    Ctrl+B     # item under Menu1 with keyboard shortcut
  Item3               # item under Menu1
  Item4               # item under Menu1

Example

In this example, we shall create a window, create a menu bar, create a menu, say Menu1, add few items to this Menu1 with keyboard shortcuts.

Menu item “Item1” has a keyboard shortcut of “Ctrl+A”.

Menu item “Item2” has a keyboard shortcut of “Ctrl+B”.

Python Program

import tkinter as tk

# Create the main window
window = tk.Tk()

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

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

# Add items for Menu1
menu_1.add_command(label="Item1", accelerator="Ctrl+A")
menu_1.add_command(label="Item2", accelerator="Ctrl+B")
menu_1.add_cascade(label="Item3")
menu_1.add_cascade(label="Item4")

# 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

Summary

In this Python Tkinter tutorial, we learned how to specify a keyboard shortcut for a menu item in Tkinter, with the help of examples.

Related Tutorials

Code copied to clipboard successfully 👍