Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Using Command

00:00 Using command Every button widget has a command attribute that you can assign to a function. Whenever the button is pressed, the function is executed.

00:12 Let’s take a look at an example. First, you create a window with a Label widget that holds a numeric value. You’ll put buttons on the left and right side of the label.

00:24 The left button will be used to decrease the value in the label, and the right one will increase the value. Here’s the code for the window.

01:07 You can see what the window looks like on screen. With the app layout defined, you can bring it to life by giving the button some commands. Start with the left button.

01:18 When this button is pressed, it should decrease the value in the label by one. In order to do this, you need the answers to two questions. How do you get the text in label?

01:29 and how do you update the text in label? Label widgets don’t have a get method like Entry and Text widgets do.

01:37 But you can retrieve the text from the label by accessing the text attribute with dictionary style subscript notation as seen on screen.

01:47 Now that you know how to get and set a label’s text, write an increase function that increases the value in label value by one increase() gets the text from label value and converts it to an integer with int().

02:02 Then it increases the value by one and sets the label’s text attribute to the new value. You’ll also need a corresponding decrease() function to decrease the value in value label by one.

02:24 To connect the buttons to the functions, assign the function to the buttons’ command attribute. You do this when you instantiate the buttons, so here you’ll update the two lines that instantiate the buttons to set command to the appropriate function.

02:48 And that’s all you need to do to make the program functional. Save the changes, and run the application.

02:58 When you click the buttons to increase and decrease the values, you should see this reflected in the center of the window.

03:09 While this app isn’t particularly useful, the skills you learned here will apply to every app you’ll make. You’ll use widgets to create the components of the user interface, you’ll use geometry managers to control the layout of the application, and you’ll write event handlers that interact with components to capture and transform user input.

03:30 In the remaining sections of the course, you’ll use these foundations to build useful applications, and next, you’ll build a temperature converter that converts from Fahrenheit to Celsius.

Become a Member to join the conversation.