";require "../templates/head_jq_bs4.php";echo "";$img_path="..";require "top-link-tkinter.php";require "templates/top_bs4.php"; echo "

Python Tkinter Combobox — set(), get(), trace_add() and ttk Widget Guide

";require "templates/body_start.php";?>


Podcast on Tkinter the Python GUI Development

Combobox allows users to select from a predefined list of options and also provides the flexibility to enter values that are not in the list.
ttk Combobox
Combobox widget is part of ttk ( What is ttk ? ) , so we have to import ttk otherwise we will get this error.
 AttributeError: module 'tkinter' has no attribute 'Combobox'

Tkinter Combobox to select Option or add data by user & reading adding and setting default options
import tkinter as tk # Importing the Tkinter libraryfrom tkinter import ttk # Importing ttk for styled widgetsmy_w = tk.Tk() # Creating the main Tkinter windowmy_w.geometry("300x150") # Setting the window size to 300x150 pixelsmy_w.title("www.plus2net.com") # Adding a title to the windowmonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'] # List of month optionscb1 = ttk.Combobox(my_w, values=months, width=7) # Creating a combobox widget with the list of monthscb1.grid(row=1, column=1, padx=10, pady=20) # Adding the combobox to the grid layoutcb1.set('Apr') # Setting 'Apr' as the default selected optionmy_w.mainloop() # Running the Tkinter event loop to display the window
By using cb1.set('Apr') we are setting a default selected option for the Combobox.
We can use the index of the option cb1.current(2) to set it as default selection.

Value and index of selected option 🔝

Here cb1 is our Combobox object
To get the selected value ( option ) we can use cb1.get()
To get the index of the selected option we can use cb1.current()

Example

ttk Combobox set & get value index
Here on click of the button b1 the value of the Combobox cb1 is set to Apr then this value and index is collected and displayed in the Label l1
The output of cb1.current() is an integer so we used str() to convert the same to string before adding.
import tkinter as tk # Importing the Tkinter libraryfrom tkinter import ttk # Importing ttk for styled widgetsmy_w = tk.Tk() # Creating the main Tkinter windowmy_w.geometry("300x150") # Setting the window size to 300x150 pixelsmy_w.title("www.plus2net.com") # Adding a title to the windowdef my_upd1(): # Function to update combobox selection    cb1.set('Apr') # Update selection to 'Apr'    l1.config(text=cb1.get() + ':' + str(cb1.current())) # Display selected value and its indexmonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'] # List of month optionscb1 = ttk.Combobox(my_w, values=months, width=7) # Creating a combobox with the list of monthscb1.grid(row=1, column=1, padx=10, pady=20) # Adding the combobox to the grid layoutb1 = tk.Button(my_w, text="set('Apr')", command=lambda: my_upd1()) # Button to update combobox selectionb1.grid(row=1, column=2) # Adding button to the gridl1 = tk.Label(my_w, text='Month') # Label to display selected month and indexl1.grid(row=1, column=3) # Adding label to the gridprint(cb1.get()) # Print the current value of the comboboxmy_w.mainloop() # Running the Tkinter event loop to display the window

Updating Label color using Combobox selection 🔝

Updating Label based on user selection of Color from Combobbox

The code generates a window with a Combobox containing several colors. When the user selects a color, the label next to it will display the color name, and the background of the label will also change to match the selected color. This makes it a simple yet effective demonstration of the interaction between Tkinter widgets.

import tkinter as tkfrom tkinter import ttk  # import ttkmy_w = tk.Tk()  # parent windowmy_w.geometry("400x150")  # Size of the windowmy_w.title("www.plus2net.com")  # Adding a titlefont1 = ['Arial', 22, 'normal']  # font styledef my_upd(*args):    l1.config(text=sel.get(), bg=sel.get())  # item name as text and background colorcolors = ['red', 'green', 'blue', 'yellow', 'lightgreen']sel = tk.StringVar()  # string variable for the Comboboxcb1 = ttk.Combobox(my_w, values=colors, width=10,                   textvariable=sel, font=font1)cb1.grid(row=1, column=1, padx=10, pady=20)l1 = tk.Label(my_w, text='Select colors', font=font1, width=10, anchor='center')l1.grid(row=1, column=2, padx=5)sel.trace_add('write', my_upd)  # trigger the change in selectionmy_w.mainloop()  # Keep the window open
Passing Data from Child window to Combobox in Parent

Clearing the selection of Combobox 🔝

In above code we are shifting the selection on click of button by using cb1.set('Apr'), same way we can reset the selection to blank by using cb1.set('') or cb1.delete(0,'end')
def my_upd1(): # Function to update or clear combobox selection    # cb1.set('') # Clear the selection (commented out)    cb1.delete(0, 'end') # Clear the current selection in the combobox    l1.config(        text=cb1.get() + ':' + str(cb1.current())    ) # Update label with the current value and index

Removing selection and from the value list 🔝

We can remove the selected option from the text ( selected ) and from the list so it can't be selected again. Note that the we will get a tuple as cb1['values'] so we can't add or remove items from this. We will create a new list and then associate the cb1['values'] to this new list after removing the selected item.
def my_delete(): # Removing option from Combobox    my_new = [] # Blank list to hold new values        for opt in cb1['values']: # Loop through all options of the combobox (tuple)        if (opt != cb1.get()): # Check if the option is not the currently selected one            # print(opt) # Debugging line to print each option (commented out)            my_new.append(opt) # Add the option to the new list        cb1['values'] = my_new # Assign the updated list back to the combobox    cb1.delete(0, 'end') # Remove the current selection text
In our script below the above code is integrated.

On Change event of Combobox 🔝

ttk Combobox Change event
Once option is selected or it is changed then we can trigger events to reflect the updation. Here we are displaying the option value in one Label l1 with the index position of the selected option ( once the selection is changed ). We used one String Variable connected to Combobox through textvariable option
import tkinter as tkfrom tkinter import ttkmy_w = tk.Tk()my_w.geometry("300x150")  # Size of the window my_w.title("www.plus2net.com")  # Adding a title
def my_upd(*args):    l1.config(text=sel.get()+ " : " + str(cb1.current()))
sel=tk.StringVar() # string variable 
months=['Jan','Feb','Mar','Apr','May','Jun']cb1 = ttk.Combobox(my_w, values=months,width=7, textvariable=sel)cb1.grid(row=1,column=1,padx=10,pady=20)
l1=tk.Label(my_w,text='Month')l1.grid(row=1,column=2)
sel.trace_add('write',my_upd)my_w.mainloop()  # Keep the window open

Adding Options to Combobox 🔝

ttk Combobox insert option
To the above code we will add one Entry box and Button. User can add data to Entry box and on click of the button b1 the user entered data will be added as option to the combobox cb1 through the function my_insert().
import tkinter as tkfrom tkinter import ttkmy_w = tk.Tk()my_w.geometry("300x150")  # Size of the window my_w.title("www.plus2net.com")  # Adding a titledef my_upd(*args):    l1.config(text=sel.get() + ' : '+ str(cb1.current()))def my_insert(): # adding data to Combobox    #if e1.get() not in cb1['values']:    cb1['values'] +=(e1.get(),) # add optionsel=tk.StringVar() # string variable months=['Jan','Feb','Mar','Apr','May','Jun']cb1 = ttk.Combobox(my_w, values=months,width=7,textvariable=sel)cb1.grid(row=1,column=1,padx=10,pady=20)l1=tk.Label(my_w,text='Month')l1.grid(row=1,column=2)
e1=tk.Entry(my_w,bg='Yellow',width=10)e1.grid(row=1,column=3)
b1=tk.Button(my_w,text='Add',command=lambda: my_insert())b1.grid(row=1,column=4)
sel.trace_add('write',my_upd)my_w.mainloop()  # Keep the window open

Preventing duplicate entry of option to Combobox 🔝

In above code we will add one if condition check inside the function my_insert() to check the string before adding. The function my_insert() code is here.
def my_insert(): # adding data to Combobox    if e1.get() not in cb1['values']: # check duplicate         cb1['values'] +=(e1.get(),) # add option

Adding Delete button to remove selected element 🔝

Delete selected option from Combobox in Tkinter
To the above code we can add one Delete button, this button on click will remove the selected item from selection and from the value list. This will remove the option from further selection. ( The part of the code is given above )

Tkinter Combobox adding or removing options by using user entered data through entry widget
import tkinter as tkfrom tkinter import ttkmy_w = tk.Tk()my_w.geometry("450x350")  # Size of the window my_w.title("www.plus2net.com")  # Adding a title
def my_insert(): # adding data to Combobox    #if e1.get() not in cb1['values']:  # prevent duplicates    cb1['values'] +=(e1.get(),) # add option    e1.delete(0,'end') # remove the current selection
def my_delete(): # removing option from the Combobox    my_new=[] # Blank list to hold new values     for opt in cb1['values']: # Loop through all options        if(opt != cb1.get()):             #print(opt)            my_new.append(opt) # Add to new list     cb1['values']=my_new # assign to new list     cb1.delete(0,'end') # remove from current selection text 
sel=tk.StringVar() # string variable 
months=['Jan','Feb','Mar']cb1 = ttk.Combobox(my_w, values=months,width=7,textvariable=sel,font=22)cb1.grid(row=1,column=1,padx=20,pady=30)
l1=tk.Label(my_w,text='Month')l1.grid(row=1,column=2)
e1=tk.Entry(my_w,bg='Yellow',width=10,font=22)e1.grid(row=1,column=3,padx=3)
b1=tk.Button(my_w,text='Add',command=lambda: my_insert(),font=18)b1.grid(row=1,column=4)
b2=tk.Button(my_w,text='Delete',command=lambda: my_delete(),font=18)b2.grid(row=1,column=5,padx=5)#sel.trace_add('write',my_upd)
my_w.mainloop()  # Keep the window open

Adding data outside of the options 🔝

ttk Combobox adding Text
User can add own data to the Combobox which is not part of the available options. Combobox also works like one Entry widget.
Here we have added Nov month and same is collected on click of the button. Note that Nov is not part of the available options.
import tkinter as tkfrom tkinter import ttkmy_w = tk.Tk()my_w.geometry("300x150")  # Size of the window my_w.title("www.plus2net.com")  # Adding a titledef my_upd1():    l1.config(text=str(cb1.current()) + ' : ' + cb1.get())
months=['Jan','Feb','Mar','Apr','May','Jun']cb1 = ttk.Combobox(my_w, values=months,width=7)cb1.grid(row=1,column=1,padx=10,pady=20)
b1=tk.Button(my_w,text="Read",command=lambda: my_upd1())b1.grid(row=1,column=2)l1=tk.Label(my_w,text='Month')l1.grid(row=1,column=3)
my_w.mainloop()  # Keep the window open

Getting numeric key and value by using dictionary 🔝

We can use the values of any dictionary as options of the Combobox and return the numeric key ( or key ).
Numeric Key as options of Combobox in Tkinter

Tkinter Combobox returning numeric key by showing value for selection of option using a dictionary


Full code is here
import tkinter as tkfrom tkinter import ttkmy_w = tk.Tk()my_w.geometry("400x150")  # Size of the windowmy_w.title("www.plus2net.com")  # Adding a titlemy_dict = {    1: 'Jan',    2: 'Feb',    3: 'March',    4: 'April',    5: 'May'}months = list(my_dict.values())  # Extract list of month namesfont1 = ('Times', 18, 'normal')def my_upd(*args):    l1.config(text=sel.get())  # Month name as string    for i, j in my_dict.items():        if j == sel.get():            l2.config(text=i)  # Month numbersel = tk.StringVar()  # String variable for the Comboboxcb1 = ttk.Combobox(my_w, values=months, width=7,                   textvariable=sel, font=font1)cb1.grid(row=1, column=1, padx=10, pady=20)l1 = tk.Label(my_w, text='Month-Name', font=font1)l1.grid(row=1, column=2, padx=5)l2 = tk.Label(my_w, text='Month-No', font=font1)l2.grid(row=1, column=3, padx=5)sel.trace_add('write', my_upd)my_w.mainloop()  # Keep the window open

Using string key in dictionary with Entry 🔝

We will get grade or GPA calculator by using Grades as Key and numbers as values. Now we will display the selected keys and values inside one Entry widget.
GPA Calculator using Combobox and Entry widget
import tkinter as tkfrom tkinter import ttkmy_w = tk.Tk()my_w.geometry("400x150")  # Size of the windowmy_w.title("www.plus2net.com")  # Adding a titlemy_dict = {'A':5, 'B':4, 'C':3,            'D':3, 'E':1, 'F':0}months = list(my_dict.keys())  # All keys are taken as optionsfont1 = ('Times', 18, 'normal')def my_upd(*args):    str1.set(sel.get())  # Key name A B C D is displayed    str2.set(my_dict[sel.get()])  # Value of the key is displayedsel = tk.StringVar()  # String variable for the Comboboxcb1 = ttk.Combobox(my_w, values=months, width=7,                    textvariable=sel, font=font1)cb1.grid(row=1, column=1, padx=10, pady=20)str1 = tk.StringVar()  # String variable for entry1str2 = tk.StringVar()  # String variable for entry2l1 = tk.Entry(my_w, font=font1, width=5, textvariable=str1)l1.grid(row=1, column=2, padx=5)l2 = tk.Entry(my_w, font=font1, width=5, textvariable=str2)l2.grid(row=1, column=3, padx=5)sel.trace_add('write', my_upd)my_w.mainloop()  # Keep the window open

Product details using dictionary 🔝

Product details on selection of Combobox

The code generates a window with a Combobox containing product names. When the user selects a product, the label next to it will display the product name, and the adjacent label will display the product details. This is a simple example demonstrating the interaction between Tkinter widgets and how to use a dictionary to provide additional details based on user selection.

import tkinter as tkfrom tkinter import ttkmy_w = tk.Tk()my_w.geometry("400x150")  # Size of the windowmy_w.title("www.plus2net.com")  # Adding a title# Item list where options of combobox are the keys of the dictionarymy_dict = {    'item 1': ['I -1', 'Medium', 40],    'item 2': ['I -2', 'High', 60],    'item 3': ['I -3', 'Low', 20],    'item 4': ['I -4', 'Best', 70]}products = list(my_dict.keys())  # List of keys as options of comboboxfont1 = ('Times', 18, 'normal')def my_upd(*args):    l1.config(text=sel.get())  # Item name as text    my_str = ",".join(map(str, my_dict[sel.get()]))  # Combine list values into a string    l2.config(text=my_str)  # Set details as textsel = tk.StringVar()  # String variable for the Comboboxcb1 = ttk.Combobox(my_w, values=products, width=7,                   textvariable=sel, font=font1)cb1.grid(row=1, column=1, padx=10, pady=20)l1 = tk.Label(my_w, text='Product', font=font1)l1.grid(row=1, column=2, padx=5)l2 = tk.Label(my_w, text='Details', font=font1)l2.grid(row=1, column=3, padx=5)sel.trace_add('write', my_upd)  # Triggers on change of StringVar (Combobox)my_w.mainloop()  # Keep the window open

Enable or disable Combobox 🔝

ttk Combobox state enable disable
The option state can take three values active, normal, disabled, readonly. We can also manage the state by using config(). Here one pair of radio buttons are used to enable or disable one Combobox.
import tkinter as tkfrom tkinter import ttkmy_w = tk.Tk()my_w.geometry("300x150+400+50")  # Size of the window my_w.title("www.plus2net.com")  # Adding a titledef my_upd():    print(r_v.get())    if r_v.get():        cb1.config(state='normal') #normal     else:        cb1.config(state='disabled')r_v=tk.BooleanVar()months=['Jan','Feb','Mar','Apr','May']cb1=ttk.Combobox(my_w,values=months,width=10)cb1.grid(row=1,column=1,padx=10,pady=10)r_v.set(True)r1 = tk.Radiobutton(my_w, text='Enable', variable=r_v,	value=True,command=my_upd)r1.grid(row=1,column=2) r2 = tk.Radiobutton(my_w, text='Disable', variable=r_v,	value=False,command=my_upd)r2.grid(row=1,column=3)my_w.mainloop()  # Keep the window open
'readonly': In this state, the user cannot type or edit the text field directly but can still select an option from the dropdown list. This is useful when we want to restrict the input to the predefined set of options only.

Attributes or Options 🔝

heightHeight of the drop-down list box.
postcommandFunction or script is called before displaying the values
exportselectionTrue / False, Managing export of selection to Clipboard
fontAssign font style , size to user entry data ( not the list ).

To change the font style of list box use this.
from tkinter.font import Font
font = Font(family = "Times", size = 24)
my_w.option_add("*TCombobox*Listbox*Font", font)
invalidcommand specifies a callback function that is called whenever the validatecommand returns False
justifyAlignment of data, takes value 'left' (default ),'center', 'right'
showChar to be used for masking the user entry and selected option
statenormal | active | disabled | readonly,
textvariableConnected variable to be used . (See the examples above)
validatedynamic validation of the widget's text content.
validatecommandcallback function that dynamically validates the widget's text content
valuesThe list of values to be included as options. ( See the examples above )
widthWidth of the combobox
xscrollcommandconnect to one Scorollbar
foregroundFont colour
backgroundBackground colour
takefocusTrue | False Widget will be included in focus traversal or not.
cursorShape of the cursor while moving over the panes. ( List of cursor shapes )
styleThe style to be used in rendering
classThe widget class name

All the options with values for Combobox 🔝

for options in cb1.config():    print(options + ": " + str(cb1[options]))

Using Google sheets data as option of Combobox 🔝

Combobox Options from Python Google sheets
We can collect data from google sheet and add as options for a Combobox by using pygsheets library and google drive API.
Options of Combobox from Google sheet data

Questions 🔝


MySQL , SQLite,CSV and Json data is used to add options for Combobox
Searched options of Combobox
Two and Three interlinked Comboboxes List of Database Tables as options of Combobox
Listbox OptionMenu Adding Combobox and text widget values