In this recipe, we will improve our GUI by adding drop-down combo boxes which can have initial default values. While we can restrict the user to only certain choices, we can also allow the user to type in whatever they wish.
Combo box widgets
Getting ready
This recipe extends the previous recipe, Setting the focus to a widget and disabling widgets.
How to do it...
We insert another column between the Entry widget and the Button widget using the grid layout manager. Here is the Python code:
This code, when added to the previous recipes, creates the following GUI. Note how, in line 43 in the preceding code, we assigned a tuple with default values to the combo box. These values then appear in the drop-down box. We can also change them if we like (by typing in different values when the application is running):
How it works...
Line 40 adds a second label to match the newly created combo box (created in line 42). Line 41 assigns the value of the box to a variable of a special tkinter type StringVar, as we did in a previous recipe.
Line 44 aligns the two new controls (label and combobox) within our previous GUI layout, and line 45 assigns a default value to be displayed when the GUI first becomes visible. This is the first value of the number_chosen['values'] tuple, the string "1". We did not place quotes around our tuple of integers in line 43, but they got casted into strings because, in line 41, we declared the values to be of the tk.StringVar type.
The preceding screenshot shows the selection made by the user as 42. This value gets assigned to the number variable.
There's more...
If we want to restrict the user to only be able to select the values we have programmed into the Combobox, we can do that by passing the state property into the constructor. Modify line 42 as follows:
Now, users can no longer type values into the Combobox. We can display the value chosen by the user by adding the following line of code to our Button Click Event Callback function:
After choosing a number, entering a name, and then clicking the button, we get the following GUI result, which now also displays the number selected: