Python tkinter OptionMenu

OptionMenu of GUI using Tkinter


Podcast on Tkinter the Python GUI Development

OptionMenu is similar to dropdown list box where user can expand and select one of the several available options.
Tkinter OptionMenu to show dropdown list box with options from List and dictionary values to users

Creating one OptionMenu

Using basics of Tkinter we will create one OptionMenu. (above Image )
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("300x200")  # Size of the window 
my_w.title("www.plus2net.com")  # Adding a title

options = tk.StringVar(my_w)
options.set("One") # default selected value

l3 = tk.Label(my_w,  text='Select One', width=15 )  
l3.grid(row=5,column=1) 

om1 =tk.OptionMenu(my_w, options, "HTML","PHP", "MySQL", "Python")
om1.grid(row=5,column=2) 
my_w.mainloop()  # Keep the window open
We can use elements of an list as options of a OptionMenu. Here we used *my_list to unpack the list return the elements as options. You can try the command print(*my_list) to display the elements of any list.
my_list = ["PHP","MySQL","Python","HTML"]
options = tk.StringVar(my_w)
options.set(my_list[1]) # default value

om1 =tk.OptionMenu(my_w, options, *my_list)
om1.grid(row=5,column=2)

Using different font family and size for the menu & options

Managing Font for OptionMenu

Managing font size of Tkinter OptionMenu #tkinter #fontsize
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("400x250")  # Size of the window 
my_w.title("www.plus2net.com")  # Adding a title

options = tk.StringVar(value='Language')
om1 =tk.OptionMenu(my_w,options,"HTML","PHP","MySQL","Python")
om1.grid(row=5,column=2,padx=100,pady=20) 

menu = my_w.nametowidget(om1.menuname)# Get menu widget.
om1.config(font=['Arial',26])  # Set Menu Font 
menu.config(font=['Arial',16])  # Set Option Font

my_w.mainloop()  # Keep the window open

Sorting the Menu Options

Sorting a List
my_list = ["PHP","MySQL","Python","HTML","JQuery"]
my_list.sort() # sort the list in alphabetical order
options = tk.StringVar(my_w)
options.set(my_list[0]) # default value

om1 =tk.OptionMenu(my_w, options, *my_list)
om1.grid(row=2,column=5) 

Adding a separator to the menu

om1['menu'].insert_separator(2) # add separator after 2nd element

How to read selected option of OptionMenu

options.get() , here options is the textvariable of OptionMenu.

Tkinter OptionMenu reading selected option & updating label on click of button, trace of StringVar

Reading selected option through button click
We will use one Button and on Click of the Button we will display the selected option of an OptionMenu inside another Label.

To the above code we will add one more Button and one Label to display the selected value of the OptionMenu. We used the function my_show() to execute once the Button is clicked.
b1 = tk.Button(my_w,  text='Show Value',command=lambda: my_show())
Inside the function my_show() we will read the value of Tkinter StringVar() options ( which is the textvariable of OptionMenu opt1 ) and display the same through our Label l2 textvariable str_out.
def my_show():
    str_out.set(options.get())
The full code is here.
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("350x200")  # Size of the window 
my_w.title("www.plus2net.com")  # Adding a title

options = tk.StringVar(my_w) # get the user selection from OptionMenu om1
options.set("Courses") # default value

l1 = tk.Label(my_w,  text='Select One', width=10 )  
l1.grid(row=2,column=1) 

om1 =tk.OptionMenu(my_w, options, "HTML","PHP", "MySQL", "Python")
om1.grid(row=2,column=2) 

b1 = tk.Button(my_w,  text='Show Value', command=lambda: my_show() )  
b1.grid(row=2,column=3) 

str_out=tk.StringVar(my_w)
str_out.set("Output") # default text on Label l2 

l2 = tk.Label(my_w,  textvariable=str_out, width=10 )  
l2.grid(row=2,column=4) 

def my_show(): # Update the Label by using StrigVariable str_out
    str_out.set(options.get()) # Update the label 

my_w.mainloop() # Keep the window open 

On Select or On Change of option of OptionMenu

Reading selected option on change or on selection
Without using any Button click we can read the selected value of the OptionMenu. Whenever any selection is changed or one option is selected by the user we will read the value and display the same through a Label. More on StringVar & trace method
Here the variable options is connected to the OptionMenu, this value whenever changes ( when user select or change the option ) the trace method will trigger the callback function my_show().

Inside this function my_show() we will update the variable str_out ( which is connected to output Label l2) by reading the new assigned value of options i.e options.get().
def my_show(*args):
    str_out.set(options.get())

options.trace('w',my_show)
Full code is here
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("300x120")  # Size of the window 
my_w.title("www.plus2net.com")  # Adding a title

l3 = tk.Label(my_w,  text='Select One', width=15 )  
l3.grid(row=2,column=1)

my_list = ["PHP","MySQL","Python","HTML"]
options = tk.StringVar(my_w)
options.set(my_list[1]) # default value

om1 =tk.OptionMenu(my_w, options, *my_list)
om1.grid(row=2,column=2)

str_out=tk.StringVar(my_w)
str_out.set("Output")

l2 = tk.Label(my_w,  textvariable=str_out, width=10 )  
l2.grid(row=2,column=4) 

def my_show(*args):
    str_out.set(options.get())

options.trace_add('write',my_show) # triggers on change of StringVar options
my_w.mainloop()  # Keep the window open

Using dictionary for OptionMenu

We have seen HTML drop down list box where the option attribute is collected but different value is shown to the visitor. So far we have used a single-element list to populate the OptionMenu here. Now we will use key value pairs or dictionary as options for the OptionMenu. Here is one sample dictionary from Category table where we have cat_id and category value as dictionary key , value pair.
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("250x200")  # Size of the window 
my_w.title("www.plus2net.com")  # Adding a title
# create the dictionary
my_dict1={1: 'Fruits', 2: 'Colors', 3: 'Games', 4: 'Vehicles'}

options = tk.StringVar(my_w) # variable 
options.set(my_dict1[1]) # default value

om1 =tk.OptionMenu(my_w, options, *my_dict1.values())
om1.grid(row=2,column=5)

def my_show(*args):  # on select function 
    for i,j in my_dict1.items():
        if j==options.get():
            print(i)            

options.trace('w',my_show)
my_w.mainloop()
Here Dictionary category ( value ) is displayed but on selection ID ( key ) is collected and displayed at console .

Dictionary keys updating a Label

Dictionary of language code is updating Lable in Tkinter
This code creates a simple Tkinter GUI window with an option menu to select a language. The languages dictionary holds language names with their two-character codes as keys.

The OptionMenu displays available languages with "Spanish" as the default selection. When the selection changes, the my_show() function finds the selected language in the dictionary and updates the label with the corresponding language code. This change is handled using trace_add, which monitors changes to the options variable, ensuring the label is updated dynamically.
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("250x200")  # Size of the window 
my_w.title("www.plus2net.com")  # Adding a title
# create the dictionary
languages = {
    "en": "English",
    "es": "Spanish",
    "fr": "French",
    "de": "German",
    "it": "Italian"
}

options = tk.StringVar(my_w) # String variable for OptionMenu
options.set(languages['es']) # default value to show

lb1=tk.Label(my_w,text='Language',width=10,bg='yellow')
lb1.grid(row=1,column=1,padx=5,pady=10)

om1 =tk.OptionMenu(my_w, options, *languages.values())
om1.grid(row=1,column=2)

def my_show(*args):  # on select function 
    for i,j in languages.items(): # i= key & j = value 
        if j==options.get(): # Matches with the selected option
             lb1.config(text=i) # Update the Label text with i 

options.trace_add('write',my_show) # triggers on change in om1 
my_w.mainloop()

Listing all available options for configuration

print(om1.config().keys()) #om1 is the OptionMenu

OptionMenu and Combobox key differences

Appearance: An `OptionMenu` widget displays the currently selected option in a label, while a Combobox widget displays the currently selected option in an `Entry` widget.

User interaction: An `OptionMenu` widget requires the user to click on the label to open the drop-down menu, while a `Combobox` widget allows the user to simply start typing to open the drop-down menu.

Flexibility: A `Combobox` widget is more flexible than an `OptionMenu` widget, as it allows the user to enter any value, not just the values that are specified when the widget is created.

When to use an OptionMenu:

  1. Use an OptionMenu when:
    • We have a limited number of options to choose from.
    • We want to make it easy for the user to select one of them.
  2. Use a Combobox when:
    • We have a large number of options to choose from.
    • We want to allow the user to enter their own value.


Add or Remove options from OptionMenu Project 1 Adding user entered text as Option of an OptionMenu.
Create one OptionMenu with option values taken from MySQL database table Create one OptionMenu with option values taken from SQLite database table
Combobox Menu
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer