Python tkinter Combobox

Basics of Python Tkinter

ttk Combobox
Combobox widget is part of 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

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

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 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())

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('w',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('w',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 data out 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

Enable or disable Combobox

ttk Combobox state enable disable
The option state can take three values active, normal, disabled. 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

Options

Some options supported by Combobox are here.

justify

Alignment of data, takes value 'left' (default ),'center', 'right'

width

Width of the Combobox. width=20

height

Height to display number of options once opened.

textvariable

Connects to variables. (See the examples above)

values

The list of values to be included as options. ( See the examples above )
MySQL , SQLite,CSV and Json data is used to add options for Combobox
Two interlinked Comboboxes
Listbox OptionMenu

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    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-2021 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer