Tkinter – OptionMenu Widget
Last Updated :
15 Mar, 2021
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:
- Import the Tkinter module.
- Create the default window
- Create a list of options to be shown at the dropdown/popup.
- Create a variable using.StringVar() method to keep track of the option selected in OptionMenu. Set a default value to it.
- Create the OptionMenu widget and pass the options_list and variable created to it.
Below is the implementation:
Python3
import tkinter
root = tkinter.Tk()
root.title( "Welcome to GeeksForGeeks" )
root.geometry( '700x500' )
options_list = [ "Option 1" , "Option 2" , "Option 3" , "Option 4" ]
value_inside = tkinter.StringVar(root)
value_inside. set ( "Select an Option" )
question_menu = tkinter.OptionMenu(root, value_inside, * options_list)
question_menu.pack()
def print_answers():
print ( "Selected Option: {}" . format (value_inside.get()))
return None
submit_button = tkinter.Button(root, text = 'Submit' , command = print_answers)
submit_button.pack()
root.mainloop()
|
Output:
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.
Share your thoughts in the comments
Please Login to comment...