Python Kivy: Build a standard calculator application – Math sign functionality
Python Kivy is a powerful open-source Python library for developing multitouch applications. In this tutorial, we will learn how to build a standard calculator application with math sign functionality using Python Kivy.
Setting up the environment
Before we start building the calculator application, make sure you have Python and Kivy installed on your system. You can install Kivy using the following command:
$ pip install kivy
Creating the UI
We will start by creating the user interface for our calculator application. Create a new Python file and add the following code:
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
class CalculatorApp(App):
def build(self):
layout = GridLayout(cols=4)
self.textinput = TextInput(multiline=False)
layout.add_widget(self.textinput)
buttons = [
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'.', '0', '=', '+'
]
for button in buttons:
btn = Button(text=button)
btn.bind(on_press=self.on_button_click)
layout.add_widget(btn)
return layout
def on_button_click(self, instance):
if instance.text == '=':
self.textinput.text = str(eval(self.textinput.text))
else:
self.textinput.text += instance.text
Adding math sign functionality
Now that we have the basic calculator UI in place, we can add math sign functionality to the application. We will modify the on_button_click
method to handle math sign buttons (+, -, *, /) properly.
def on_button_click(self, instance):
if instance.text == '=':
self.textinput.text = str(eval(self.textinput.text))
elif instance.text in ['+', '-', '*', '/']:
if self.textinput.text and self.textinput.text[-1] in ['+', '-', '*', '/']:
self.textinput.text = self.textinput.text[:-1]
self.textinput.text += instance.text
else:
self.textinput.text += instance.text
Running the application
With the math sign functionality added, you can now run the calculator application by adding the following code to the bottom of the Python file:
if __name__ == '__main__':
CalculatorApp().run()
Save the file and run it using the Python interpreter. You should see a basic calculator application with math sign functionality that allows you to perform simple arithmetic calculations.
Python Kivy provides a simple and effective way to build intuitive and interactive user interfaces for applications. By following this tutorial, you have learned how to create a standard calculator application with math sign functionality using Python Kivy.