What is OptionMenu widget?

The OptionMenu widget is used to create a popup menu, that displays a list of options from where the user can select one option at a time. It is much similar to the combo box.

Example

The following python script creates a window containing one OptionMenu with some options, from where the user can select one option at a time. Whenever the user clicks on the show button it prints the selected item on the console.

You need to write following code in any text editor and then save it with .py extension. To execute the application, Type py OptionMenuExample.py command in terminal. 

from tkinter import *

# Top level window 
window = Tk()

window.title("Studyfied.com")
window.geometry('350x200')

# Option menu variable
optionVar = StringVar()
optionVar.set("Red")

# Create a option menu
option = OptionMenu(window, optionVar, "Red", "Blue", "White", "Black")
option.pack()

# Create button with command
def show():
    print("Selected value :", optionVar.get())

btnShow = Button(window, text="Show", command=show)
btnShow.pack()

window.mainloop()

Output

The above code produces the following output in windows operating system.

Explanation

Following line creates a Tkinter window

from tkinter import *

window = Tk()

window.title("Studyfied.com")
window.geometry('350x200')

See explanation of Tkinter window – Tkinter top level window


This snippet creates a Tkinter variable, which is bound to OptionMenu. It is used to get the currently selected option from OptionMenu or to set current value for the menu. Here “Red” is set as current value.

# Option menu variable
optionVar = StringVar()
optionVar.set("Red")

These two lines create an OptionMenu widget. The first parameter is parent widget or window, here it is the window, and remaining parameters are options for OptionMenu.

# Create a option enu
option = OptionMenu(window, optionVar, "Red", "Blue", "White", "Black")
option.pack()

The second line option.pack(), is geometry manager that packs widgets into rows or columns.


This snippet creates a button with command whenever the user clicks on it, It takes the selected value from OptionMenu and displays it in the console. 

# Create button with command
def show():
    print("Selected value :", optionVar.get())

btnShow = Button(window, text="Show", command=show)
btnShow.pack()

See how to use buttons – Tkinter button widget