Creating a Basic Calculator App with Python Kivy: Adding Button Functionality (Part 1)

Posted by

Python Kivy: Build a standard calculator application – Buttons functionality part 1

Python Kivy: Build a standard calculator application – Buttons functionality part 1

Python Kivy is a powerful open-source Python library for developing multi-touch applications. In this tutorial, we will learn how to build a standard calculator application using Python Kivy. In this part, we will focus on implementing the functionality of the calculator buttons.

Creating Buttons

First, let’s create the buttons for our calculator application. We will need buttons for numbers 0-9, as well as buttons for addition, subtraction, multiplication, division, and equals.

“`python
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.app import App

class CalculatorApp(App):
def build(self):
layout = GridLayout(cols=4)

# Create number buttons
for i in range(1, 10):
button = Button(text=str(i))
layout.add_widget(button)

# Create operation buttons
operations = [‘+’, ‘-‘, ‘*’, ‘/’]
for operation in operations:
button = Button(text=operation)
layout.add_widget(button)

# Create equal button
equal_button = Button(text=’=’)
layout.add_widget(equal_button)

return layout

if __name__ == ‘__main__’:
CalculatorApp().run()
“`

Button Functionality

Now that we have created the buttons, let’s add functionality to each button. For the number buttons, we will simply update the display with the corresponding number when clicked. For the operation buttons, we will store the operation in a variable to be used when the equals button is clicked.

“`python
class CalculatorApp(App):
def build(self):
layout = GridLayout(cols=4)

# … (button creation code)

# Function to update display
def update_display(instance):
if instance.text in ‘1234567890’:
# Update display with number
self.display.text += instance.text

# Add click functionality to number buttons
for i in range(1, 10):
button = Button(text=str(i))
button.bind(on_press=update_display)
layout.add_widget(button)

# … (operation buttons creation code)

# Functionality for operation buttons
def store_operation(instance):
self.operation = instance.text
self.first_number = int(self.display.text) if self.display.text else 0
self.display.text = ”

# Add click functionality to operation buttons
for operation in operations:
button = Button(text=operation)
button.bind(on_press=store_operation)
layout.add_widget(button)

# … (equal button creation code)

return layout
“`

With the above code, we have added functionality to the number buttons to update the display with the corresponding number when clicked, and the operation buttons to store the operation in a variable to be used when the equals button is clicked. In the next part, we will implement the functionality for the equals button and complete the calculator application.