How to Create Dropdown Menu in Tkinter

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 a bit similar to Combobox widget but is already included in the Tkinter itself, therefore, you don’t need to import ttk like in the case of Combobox.

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

Tkinter OptionMenu Example

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