Python tkinter Combobox


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
from tkinter import ttk
my_w = tk.Tk()
my_w.geometry("300x150")  # Size of the window 
my_w.title("www.plus2net.com")  # Adding a title
months=['Jan','Feb','Mar','Apr','May','Jun'] # options
cb1 = ttk.Combobox(my_w, values=months,width=7) # Combobox
cb1.grid(row=1,column=1,padx=10,pady=20) # adding to grid
cb1.set('Apr') # default selected option
my_w.mainloop()  # Keep the window open
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.

getting 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
from tkinter import ttk
my_w = tk.Tk()
my_w.geometry("300x150")  # Size of the window 
my_w.title("www.plus2net.com")  # Adding a title
def my_upd1():
    cb1.set('Apr') # update selection to Apr
    l1.config(text=cb1.get()+':'+ str(cb1.current())) # value & index

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="set('Apr')", command=lambda: my_upd1())
b1.grid(row=1,column=2)

l1=tk.Label(my_w,text='Month')
l1.grid(row=1,column=3)
print(cb1.get())
my_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():
    #cb1.set('') # Clear the selection 
    cb1.delete(0,'end') # clear the selection
    l1.config(text=cb1.get()+':'+ str(cb1.current())) # value & 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 tuple
        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 
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 tk
from tkinter import ttk
my_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 tk
from tkinter import ttk
my_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()))
def my_insert(): # adding data to Combobox
    #if e1.get() not in cb1['values']:
    cb1['values'] +=(e1.get(),) # add option
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)

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 tk
from tkinter import ttk
my_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 tk
from tkinter import ttk
my_w = tk.Tk()
my_w.geometry("300x150")  # Size of the window 
my_w.title("www.plus2net.com")  # Adding a title
def 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 tk
from tkinter import ttk
my_w = tk.Tk()
my_w.geometry("400x150")  # Size of the window 
my_w.title("www.plus2net.com")  # Adding a title
my_dict={1:'Jan',2:'Feb',3:'March',4:'April',5:'May'}
months=list(my_dict.values())
#months=['Jan','Feb']
font1=('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 number

sel=tk.StringVar() # string variable for the Combobox
cb1=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 tk
from tkinter import ttk
my_w = tk.Tk()
my_w.geometry("400x150")  # Size of the window 
my_w.title("www.plus2net.com")  # Adding a title
my_dict={'A':5,'B':4,'C':3,'D':3,'E':1,'F':0} 
months=list(my_dict.keys()) # All keys are taken as options 
font1=('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 displayed

sel=tk.StringVar() # string variable for the Combobox
cb1=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() # for entry1
str2=tk.StringVar() # for entry2

l1=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

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 tk
from tkinter import ttk
my_w = tk.Tk()
my_w.geometry("300x150+400+50")  # Size of the window 
my_w.title("www.plus2net.com")  # Adding a title
def my_upd():
    print(r_v.get())
    if r_v.get():
        cb1.config(state='active') #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
valuesThe list of values to be included as options. ( See the examples above )
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
valuesOptions that will appear as choice.
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
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    29-07-2022

    Dear Sir,
    Thank you for your good instructions. I learn a lot from your videos.
    One question:
    how to delete the combobox option dynamicly?
    i was unable to use cb1['values'] -=(e1.get(),) to delete the option.
    please kindly teach me how to do it.

    Thank you very much.
    I subcribed your yourtube already.

    ST

    05-08-2022

    You can't delete by using cb1['values'] -=(e1.get(),) as it is a tuple. Create a new tuple with all the options except the one you want to delete. Then assign the new tuple to cb1.
    This part is added to this page. Here is the video again.

    https://youtu.be/PICzrYI6O9A

    22-11-2022

    In one of the programs which i am working , the combo box freezes when i click on dropdown and then the application stops and crashes. Please advise

    08-01-2023

    Are you using any onclick event and triggering any function? Just remove the function and see how it is working. Then check the code inside the function.

    Post your comments , suggestion , error , requirements etc here





    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