Create Dropdown Menu in Tkinter

  1. Tkinter OptionMenu Example
  2. Bind Command to OptionMenu When Value Changes

It has some methods to create a dropdown menu in Tkinter.

  1. Use Combobox as introduced in the Tkinter tutorial Combobox chapter.
  2. Use OptionMenu Widget.

The OptionMenu is similar to the Combobox widget but is already included in the Tkinter itself; therefore, you don’t need to import ttk module like in the case of Combobox.

We will introduce how to create a dropdown menu with the OptionMenu widget in this article.

Tkinter OptionMenu Example

import tkinter as tk

OptionList = [
"Aries",
"Taurus",
"Gemini",
"Cancer"
] 

app = tk.Tk()

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()

app.mainloop()

Tkinter OptionMenu Example

opt = tk.OptionMenu(app, variable, *OptionList)

app is the parent of the created option menu,

variable is the initial text variable that has tk.StringVar type.

*OptionList is the other menu options. * is used for unpacking the container as list type here.

Bind Command to OptionMenu When Value Changes

OptionMenu couldn’t link a command when a new value is selected from the option list. You couldn’t simply link a callback function to it like button widget

tk.Button(app, text="Increase", width=30, command=change_label_number)

You need to use a trace method to attach observer callbacks to the OptionMenu variable. Every time the variable changes, it triggers the callback functions.

OptionMenu Callback Example

import tkinter as tk

OptionList = [
"Aries",
"Taurus",
"Gemini",
"Cancer"
] 

app = tk.Tk()

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")


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

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

variable.trace("w", callback)

app.mainloop()

The trace observer has three modes,

observer mode Explanation
w when variable is written by someone
r when variable is read by someone
u when variable is deleted

Then variable.trace("w", callback) means it will call callback function when variable is written or selected by the user.

Tkinter OptionMenu Callback

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.