Create a Kivy Application
00:01 Creating a Kivy Application. One of the best ways to learn a new skill is by creating something useful. With that in mind, you’ll use Kivy to build a calculator that supports the following operations: addition, subtraction, multiplication, and division.
00:18 For this application, you’ll need a series of buttons in a layout. You’ll also need a box along the top of your app to display the equations and their results. On-screen, you can see a sketch of the calculator.
In this line, you start a
for loop over those buttons. For each nested list, you’ll do the following: Create a
BoxLayout with horizontal orientation, start another
for loop over the items in the nested list, create the buttons for the row,
As you’ve already seen, most of the widgets in the application call
.on_button_press(), so that’s what you’ll be coding next. The method definition takes the
instance argument so you can access which widget called the function.
If they pressed any other key, then the program moves onto the
else statement. This checks if the solution has any preexisting value. And here you check if the last button that was pressed was an operator button.
If none of the previous conditions are met, then
solution is updated with the
last_button is set to the label of the last button pressed, and
last_was_operator is set to
False depending on whether or not it was an operator character.
The last piece of code to write is
.on_solution(). Here, you get the current text from
solution and use Python’s built-in
eval() to execute it. If the user created a formula such as
eval() will run the code and return the result. Finally, you set the result as a new value for the
eval() is somewhat dangerous because it can run arbitrary code. Most developers avoid using it because of that fact. However, since you’re only allowing integers, operators, and the period as input to
eval(), it should be safe to use in this context.
Become a Member to join the conversation.