How to create drop-down menu in Tkinter in Python

In this blog, we are going to see how we can create a drop-down menu in Python using Tkinter.

The Dropdown Menu is mostly used while filling forms and providing multiple options to select in any given menu.
It is a very convenient and space-saving way of proving multiple options because the space taken by the option is only temporary and goes away as soon as we move on from that very field.

Tkinter library has been used in the following code to create a GUI with a dropdown menu.
Tkinter is Pythons defacto GUI library. It is not the only GUI toolkit in Python but is the most commonly used one.
The library is packed with methods that can be used to create apps and a variety of GUIs with utmost ease and simplicity.

Python program to create a dropdown menu in Tkinter

#Importing library
import tkinter as tk

#Defining option list
OptionList = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
]

app = tk.Tk()

#Font and orientation setup
app.geometry('100x200')

variable = tk.StringVar(app)
variable.set(OptionList[0])

opt = tk.OptionMenu(app, variable, *OptionList)
opt.config(width=90, font=('Helvetica', 12))
opt.pack(side="top")

#Label
labelTest = tk.Label(text="", font=('Helvetica', 12), fg='red')
labelTest.pack(side="top")

#Function
def callback(*args):
    labelTest.configure(text="The selected item is {}".format(variable.get()))

variable.trace("w", callback)

app.mainloop()

Code Explained

First of all, we import the desired library, which is Tkinter as tk.
The next comes defining what the options list will contain.
It is followed by the font and orientation settings which decide how the GUI should look and what its specifications should be.
After this, we write the code responsible for the label display and the code responsible for the calling of functions.

Output

Python program to create a dropdown menu in Tkinter

Background

The dropdown menu helps to show a large list of choices and only one choice is displayed until the user clicks on the dropdown box to access it. These are usually found in all types of software ranging from operating systems to banking and form filling software.

Mostly all the e-commerce websites use this so that they can show a large variety of choices on their interface and can also facilitate large scale input by their users.

The three main issues when one needs to use the drop-down menu are the following ones:

1.  Lack of Overview
2. Scrolling Issues
3. Inconsistent UI

Also read: Detect keypress in Tkinter in Python

Leave a Reply

Your email address will not be published. Required fields are marked *