Python Tkinter Combobox
A special extension of Python Tkinter, the ttk module brings forward this new widget. The Python Tkinter Combobox presents a drop down list of options and displays them one at a time. It’s good for places where visibility is important and has a modern look to it.
The Python Combobox is actually a sub class of the widget Entry . Hence it inherits many options and methods from the Entry class as well as bringing some new ones of it’s to the table.
ComboBox Syntax
You must specially import the ttk module to be able to use Comboboxes.
from tkinter import ttk Combo = ttk.Combobox(master, values. )
Assigning a ComboBox Values
In the example we create a list of values, and then feed them to the values option in the Combobox.
By Default the Combobox is spawned with no value selected. In other words, it’s blank. If you wish, you can avoid this using the set() function.
from tkinter import * from tkinter import ttk root = Tk() root.geometry("200x150") frame = Frame(root) frame.pack() vlist = ["Option1", "Option2", "Option3", "Option4", "Option5"] Combo = ttk.Combobox(frame, values = vlist) Combo.set("Pick an Option") Combo.pack(padx = 5, pady = 5) root.mainloop()
If the ComboBox was not what you were looking for, it has a variant called the SpinBox which may interest you.
Retrieving Combobox values
Once the user has selected an option, we need a way to retrieve his input. For this we need a button which the User must trigger. The button calls a function that uses the get() function to retrieve the current value of the Combobox.
from tkinter import * from tkinter import ttk def retrieve(): print(Combo.get()) root = Tk() root.geometry("200x150") frame = Frame(root) frame.pack() vlist = ["Option1", "Option2", "Option3", "Option4", "Option5"] Combo = ttk.Combobox(frame, values = vlist) Combo.set("Pick an Option") Combo.pack(padx = 5, pady = 5) Button = Button(frame, text = "Submit", command = retrieve) Button.pack(padx = 5, pady = 5) root.mainloop()
Video Code
import tkinter as tk from tkinter import ttk class Window: def __init__(self, master): self.master = master # Frame self.frame = tk.Frame(self.master, width = 200, height = 200) self.frame.pack() self.vlist = ["Option1", "Option2", "Option3", "Option4", "Option5"] self.combo = ttk.Combobox(self.frame, values = self.vlist, state = "readonly") self.combo.set("Pick an Option") self.combo.place(x = 20, y = 50) root = tk.Tk() root.title("Tkinter") window = Window(root) root.mainloop()
This marks the end of the Tkinter Combobox article. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article content can be asked in the comments section below.
You can head back to the main Tkinter article using this link.
Tkinter Combobox
Summary: in this tutorial, you’ll learn to create a Tkinter combobox widget that allows users to select one value from a set of values.
Introduction to the Tkinter Combobox widget
A combobox is a combination of an Entry widget and a Listbox widget. A combobox widget allows you to select one value in a set of values. In addition, it allows you to enter a custom value.
Create a combobox
To create a combobox widget, you’ll use the ttk.Combobox() constructor. The following example creates a combobox widget and links it to a string variable:
current_var = tk.StringVar() combobox = ttk.Combobox(container, textvariable=current_var)
Code language: Python (python)
The container is the window or frame on which you want to place the combobox widget.
The textvariable argument links a variable current_var to the current value of the combobox.
To get the currently selected value, you can use the current_var variable:
current_value = current_var.get()
Code language: Python (python)
Alternatively, you can use the get() method of the combobox object:
current_value = combobox.get()
Code language: Python (python)
To set the current value, you use the current_var variable or the set() method of the combobox object:
current_value.set(new_value) combobox.set(new_value)
Code language: Python (python)
Define value list
The combobox has the values property that you can assign a list of values to it like this:
combobox['values'] = ('value1', 'value2', 'value3')
Code language: Python (python)
By default, you can enter a custom value in the combobox. If you don’t want this, you can set the state option to ‘readonly’ :
combobox['state'] = 'readonly'
Code language: Python (python)
To re-enable editing the combobox, you use the ‘normal’ state like this:
combobox['state'] = 'normal'
Code language: Python (python)
Bind events
When a select value changes, the combobox widget generates a ‘>’ virtual event. To handle the event, you can use the bind() method like this:
combobox.bind('>', callback)
Code language: Python (python)
In this example, the callback function will execute when the selected value of the combobox changes.
Set the current value
To set the current value, you use the set() method:
combobox.set(self, value)
Code language: Python (python)
Also, you can use the current() method:
current(self, newindex=None)
Code language: Python (python)
The newindex specifies the index of values from the list that you want to select as the current value.
If you don’t specify the newindex , the current() method will return the index of the current value in the list of values or -1 if the current value doesn’t appear in the list.
Python Tkinter combobox example
The following program illustrates how to create a combobox widget:
import tkinter as tk from tkinter import ttk from tkinter.messagebox import showinfo from calendar import month_name root = tk.Tk() # config the root window root.geometry('300x200') root.resizable(False, False) root.title('Combobox Widget') # label label = ttk.Label(text="Please select a month:") label.pack(fill=tk.X, padx=5, pady=5) # create a combobox selected_month = tk.StringVar() month_cb = ttk.Combobox(root, textvariable=selected_month) # get first 3 letters of every month name month_cb['values'] = [month_name[m][0:3] for m in range(1, 13)] # prevent typing a value month_cb['state'] = 'readonly' # place the widget month_cb.pack(fill=tk.X, padx=5, pady=5) # bind the selected value changes def month_changed(event): """ handle the month changed event """ showinfo( title='Result', message=f'You selected !' ) month_cb.bind('>', month_changed) root.mainloop()
Code language: Python (python)
The following program shows the same month combobox widget and uses the set() method to set the current value to the current month:
import tkinter as tk from tkinter import ttk from tkinter.messagebox import showinfo from calendar import month_name from datetime import datetime root = tk.Tk() # config the root window root.geometry('300x200') root.resizable(False, False) root.title('Combobox Widget') # label label = ttk.Label(text="Please select a month:") label.pack(fill=tk.X, padx=5, pady=5) # create a combobox selected_month = tk.StringVar() month_cb = ttk.Combobox(root, textvariable=selected_month) # get first 3 letters of every month name month_cb['values'] = [month_name[m][0:3] for m in range(1, 13)] # prevent typing a value month_cb['state'] = 'readonly' # place the widget month_cb.pack(fill=tk.X, padx=5, pady=5) # bind the selected value changes def month_changed(event): """ handle the month changed event """ showinfo( title='Result', message=f'You selected !' ) month_cb.bind('>', month_changed) # set the current month current_month = datetime.now().strftime('%b') month_cb.set(current_month) root.mainloop()
Code language: Python (python)
Summary
- Use ttk.Combobox(root, textvariable) to create a combobox.
- Set the state property to readonly to prevent users from entering custom values.
- A combobox widget emits the ‘>’ event when the selected value changes.