Tkinter dropdown Menu with keyboard shortcuts


A Dropdown Menu is nothing but a list of vertically stacked menu items that can be visible at the top Menu Bar of an application. We can create a Menu bar in a Tkinter application by creating an object of Menu() in which all the Menu items are present.

There might be a case when we want to select the menu and perform some basic operations using Keyboard shortcuts. In order to bind the key to all the Menu, we use the bind_all(<Key>, callback) method.

Example

In this example, the application window contains a Menu of items. When we press the combination of <Ctrl + Q>, it will close the Main window.

#Import the required libraries
from tkinter import *

#Create an instance of Tkinter Frame
win = Tk()

#Set the geometry
win.geometry("750x350")

def exit():
   win.destroy()

#Create a Menu Bar
menubar= Menu()
filemenu= Menu(menubar, tearoff=False)
menubar.add_cascade(label= "File",underline=0, menu= filemenu)
filemenu.add_command(label="1.a", underline= 1)
filemenu.add_command(label="2.b", underline= 1)
filemenu.add_command(label="3.c", underline= 1)
filemenu.add_command(label="Quit", underline= 1, command= exit, accelerator= "Ctrl+Q")
win.config(menu= menubar)
filemenu.bind_all("<Control-q>", exit)

win.mainloop()

Output

Running the above code will display a window that contains a Label text and a Menu on the Menu Bar.

Now, click the menu item "Quit" or press <Ctrl+ Q> to close the main window.

Updated on: 25-May-2021

810 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements