Drop-down List (Combobox) in Tk (tkinter)
The drop-down list is known in the GUI jargon as Combobox, since it is a combo between a listbox and a textbox. Thus, it can act as a drop-down list with predefined options and might also allow the user to type a value that is not in the list.
The widget was introduced in Tk 8.5 and is provided via the ttk.Combobox
class, which inherits from the textbox widget ttk.Entry
, so all operations applicable to a textbox also apply to a combobox.
The following code creates a simple window with an empty drop-down list.
If we want the widget to behave only as a drop-down list, thus not allowing the user to enter their own values, we instantiate it as read-only:
To configure a set of options, we pass a list to the values
argument:
A combobox in Tk only works with strings. Other data types will be automatically converted before being added to the list.
The get()
method returns the selected option, either if it has been picked from the list or manually written by the user (if the widget is not read-only). For example, the following code uses a message box to display the selected option in the drop-down list after pressing a button.
The get()
method always returns a string. If there is no selection, an empty string is returned.
It is also possible to get the index (i.e., the position of an option within the list, starting from 0
) of the selected element via the current()
method. If no element is selected, or if the element is not among the provided options (that is, it has been typed by the user), the return value is -1
.
Similarly, the set()
method sets the currently selected option.
To select an option by position or index, the current()
method is also used, although passing the element to be selected as an argument:
To get all the options configured in the drop-down:
Note that the returned value is a tuple, not a list. To add an option without dropping those already in the drop-down, use:
And to remove all the options:
Events¶
The ttk.Combobox
widget introduces a new event called <<ComboboxSelected>>
that is sent when the selected option changes. This way, it is possible to set up a function to be executed every time the user changes the drop-down selection. For example:
Note that this event does not record changes entered manually by the user.
We can pass a function to the postcommand
parameter to get notified when the drop-down has been opened (i.e., the arrow on right has been pressed):