How to call a function using the OptionMenu widget in Tkinter?


Let's take an example and see how to call a function using OptionMenu widget in Tkinter. In the example, we will use a StringVar object and call its get() method. A StringVar object in Tkinter can help manage the value of a widget.

We will create an OptionMenu widget and fill it with a list of strings. When the user selects an option, it will invoke a function which in turn will print the selected option as a label.

Steps −

  • Import the tkinter library and create an instance of tkinter frame.

  • Set the size of the frame using geometry method.

  • Create a set of strings and save it in a variable, data.

  • Next, use the StringVar() constructor to create a StringVar object. It helps to manage the value of a widget, which is an OptionMenu in this case.

  • Create a list of strings "options" and an OptionMenu. Set the values of the OptionMenu by passing the StringVar object and "options".

  • Create a label to display the selected option from the OptionMenu.

  • Create a user-defined function "OptionMenu_Select" to print the selected item from the OptionMenu in the label.

  • Use the parameter command=OptionMenu_Select to invoke the user-defined function when the user selects an option.

  • Finally, run the mainloop of the application window.

Example

# Import the tkinter library
from tkinter import *

# Create an instance of tkinter frame
root = Tk()
root.geometry("700x300")

# Create the option and Check Button Event
def OptionMenu_Select(event):
label_city.config(text="You have selected: " + var.get())

# Create the variables
var = StringVar();
var.set("Select a City")

options = ["Mumbai", "Chennai", "Bhubaneswar", "Pune", "Patna", "Bhopal", "Surat", "Hyderabad", "New Delhi", "Lucknow"]
OptionMenu(root, var, *(options), command=OptionMenu_Select).pack(pady=50)

label_city=Label(root, font="Calibri,12,bold")
label_city.pack(padx=20, pady=20)

root.mainloop()

Output

It will produce the following output −

When the user selects an option, it will display the selected option as a label −

Updated on: 26-Oct-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements