Python Kivy: Build a standard calculator application – Buttons functionality part 4
In the previous parts of this tutorial series, we discussed how to create the UI layout and add functionality for basic mathematical operations in our calculator application. In this part, we will focus on adding functionality to the different buttons of the calculator.
Let’s start by defining the buttons for the numeric digits (0-9) and the arithmetic operators (+, -, *, /) in our calculator.
<Button text="1" on_press: root.add_text('1') /> <Button text="2" on_press: root.add_text('2') /> ... <Button text="+" on_press: root.add_text('+') /> <Button text="-" on_press: root.add_text('-') /> ...
Next, we need to define the function add_text
in our Python code to handle the input from these buttons. This function will update the text input field with the clicked button’s value.
def add_text(self, text): current_text = self.ids['input_field'].text new_text = current_text + text self.ids['input_field'].text = new_text
Now, when a user clicks on any numeric digit or arithmetic operator button, the corresponding value will be appended to the input field.
Finally, we need to add functionality to the ‘=’ button to calculate the result of the expression entered by the user. We can define a similar function to handle this calculation.
def calculate_result(self): expression = self.ids['input_field'].text try: result = eval(expression) self.ids['input_field'].text = str(result) except Exception as e: self.ids['input_field'].text = 'Error'
With these functionalities in place, our calculator application now has the ability to handle input from the different buttons and calculate results accordingly.
Stay tuned for the next part of this tutorial series where we will add additional features to our calculator application.