In this recipe, we will add a button widget, and we will use this button to change a property of another widget that is a part of our GUI. This introduces us to callback functions and event handling in a Python GUI environment.
This recipe extends the previous one, Adding a label to the GUI form. You can download the entire code from https://github.com/PacktPublishing/Python-GUI-Programming-Cookbook-Second-Edition/.
We add a button that, when clicked, performs an action. In this recipe, we will update the label we added in the previous recipe as well as the text property of the button:
GUI_create_button_change_property.py
The following screenshot shows how our GUI looks before clicking the button:
After clicking the button, the color of the label changed and so did the text of the button, which can be seen as follows:
In line 19, we assign the label to a variable, and in line 20, we use this variable to position the label within the form. We need this variable in order to change its properties in the click_me()
function. By default, this is a module-level variable, so we can access it inside the function, as long as we declare the variable above the function that calls it.
Line 23 is the event handler that is invoked once the button gets clicked.
In line 29, we create the button and bind the command to the click_me()
function.
Note
GUIs are event-driven. Clicking the button creates an event. We bind what happens when this event occurs in the callback function using the command property of the ttk.Button
widget. Notice how we do not use parentheses, only the name click_me
.
We also change the text of the label to include red
as, in the printed book, this might otherwise not be obvious. When you run the code, you can see that the color does indeed change.
Lines 20 and 30 both use the grid layout manager, which will be discussed in the following chapter. This aligns both the label and the button.