Open In App

Tkinter – OptionMenu Widget

Last Updated : 15 Mar, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite: Python GUI -tkinter

One of the most popular Python modules to build GUI(Graphical User Interface) based applications is the Tkinter module. It comes with a lot of functionalities like buttons, text-boxes, labels to be used in the GUI application, these are called widgets. In this article, we are going to learn what is the OptionMenu Widget and when it is used.

What is OptionMenu widget?

OptionMenu is basically a dropdown or popup menu that displays a group of objects on a click or keyboard event and lets the user select one option at a time.

Approach:

  1. Import the Tkinter module.
  2. Create the default window
  3. Create a list of options to be shown at the dropdown/popup.
  4. Create a variable using.StringVar() method to keep track of the option selected in OptionMenu. Set a default value to it.
  5. Create the OptionMenu widget and pass the options_list and variable created to it.

Below is the implementation:

Python3




# Import the tkinter module
import tkinter
  
# Create the default window
root = tkinter.Tk()
root.title("Welcome to GeeksForGeeks")
root.geometry('700x500')
  
# Create the list of options
options_list = ["Option 1", "Option 2", "Option 3", "Option 4"]
  
# Variable to keep track of the option
# selected in OptionMenu
value_inside = tkinter.StringVar(root)
  
# Set the default value of the variable
value_inside.set("Select an Option")
  
# Create the optionmenu widget and passing 
# the options_list and value_inside to it.
question_menu = tkinter.OptionMenu(root, value_inside, *options_list)
question_menu.pack()
  
# Function to print the submitted option-- testing purpose
  
  
def print_answers():
    print("Selected Option: {}".format(value_inside.get()))
    return None
  
  
# Submit button
# Whenever we click the submit button, our submitted
# option is printed ---Testing purpose
submit_button = tkinter.Button(root, text='Submit', command=print_answers)
submit_button.pack()
  
root.mainloop()


Output:

opetionmenu tkinter

Explanation: 

In the output GUI window, an OptionMenu widget is created it contains the default value of “Select an Option” as given. On click, it shows a dropdown containing the given options list.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads