How to create Option Menu in Tkinter ?
Last Updated :
31 Aug, 2021
The Tkinter package is the standard GUI (Graphical user interface) for python, which provides a powerful interface for the Tk GUI Toolkit. In this tutorial, we are expecting that the readers are aware of the concepts of python and tkinter module.
OptionMenu
In this tutorial, our main focus is to create option menu using tkinter in python. As the name suggests, option menu is a list of options for the user in simple language. This can be achieved using OptionMenu class, which creates a pop-up menu and displays the options that the user can avail.
we can create an option menu by initializing the constructor of that class.
Syntax: OptionMenu(parent, variable, choice_1, choice_2, choice_3, …)
- parent- This is a parent object which is also called as master object. It’s main role is to create the window for GUI and also keep other widgets used in the program.
- variable- This is the default name that should be shown to the option menu.
- choice_1, choice_2, choice_3, …- These are the actual list of options that are available for the user.
As OptionMenu is a class, so obviously there will be some methods in it. Let’s study some methods one-by-one.
- get() method- This method of OptionMenu return the value which is currently selected from the option menu.
- mainloop() method- This method is not only the part of OptionMenu class but also the part of whole tkinter package. It’s role is to combine all the widgets in our program before we run it and hence used at the end when we are done with our code.
- place() method- This method keeps all the widgets at the specified position by the programmer.
- pack() method- This method helps in arranging the OptionMenu in a specific position.
Let us now have a lot at some examples which will make our concepts more clear.
This is a basic example to create a simple option menu.
Example 1:
Python3
from tkinter import *
parent = Tk()
variable = StringVar(parent)
variable. set ( "COLOURS" )
option_menu = OptionMenu(parent, variable, "Yellow" ,
"Blue" , "Green" , "Purple" ,
"Black" , "White" )
option_menu.pack()
parent.mainloop()
|
Output:
Example 2:
Python3
import tkinter as tk
parent = tk.Tk()
parent.title( "Geeksforgeeks- OptionMenu" )
Age_Variable = tk.StringVar(parent)
Age_Variable. set ( "Age" )
Age_Option = tk.OptionMenu(parent, Age_Variable,
"below 14" , "15" ,
"16" , "17" ,
"above 18" )
Age_Option.pack()
Gender_Variable = tk.StringVar(parent)
Gender_Variable. set ( "Gender" )
Gender_Option = tk.OptionMenu(parent,
Gender_Variable,
"Male" , "Female" )
Gender_Option.pack()
Hobby_Variable = tk.StringVar(parent)
Hobby_Variable. set ( "Hobby" )
Hobby_Option = tk.OptionMenu(parent, Hobby_Variable,
"Dance" , "Code" , "Sing" ,
"Draw" )
Hobby_Option.pack()
parent.mainloop()
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...