Building a Python Calculator with Kivy

Posted by


In this tutorial, we will be creating a basic calculator using the Kivy library in Python. Kivy is an open-source Python library for developing multitouch applications. It provides a fast and easy way to create cross-platform applications for desktop and mobile devices.

To get started, you will need to have Python and Kivy installed on your machine. You can install Kivy using pip by running the following command:

pip install kivy

Once you have Kivy installed, you can create a new Python script and follow along with the steps below to create the calculator.

Step 1: Import the necessary modules

First, we need to import the necessary modules from Kivy, such as App, GridLayout, Button, and Label. Create a new Python script 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.label import Label

Step 2: Create the Calculator class

Next, we will create a new class called Calculator that inherits from the GridLayout class. The GridLayout class arranges its children in a grid layout. Add the following code to your script:

class Calculator(GridLayout):
    def __init__(self, **kwargs):
        super(Calculator, self).__init__(**kwargs)
        self.cols = 4

Step 3: Create the buttons and labels

In the init method of the Calculator class, we will create the buttons for numbers, operators, and the equal sign. We will also create a Label widget to display the result. Add the following code to your script:

        self.result = Label(text='0', font_size=50)
        self.add_widget(self.result)

        buttons = [
            '7', '8', '9', '/',
            '4', '5', '6', '*',
            '1', '2', '3', '-',
            '.', '0', '=', '+'
        ]

        for btn in buttons:
            self.add_widget(Button(text=btn))

Step 4: Define the event handlers

Next, we will define event handlers for the button clicks. We will create a method called on_button_click that will be called when a button is clicked. Add the following code to your script:

    def on_button_click(self, button):
        if button.text == '=':
            try:
                self.result.text = str(eval(self.result.text))
            except:
                self.result.text = 'Error'
        else:
            if self.result.text == '0' or self.result.text == 'Error':
                self.result.text = button.text
            else:
                self.result.text += button.text

Step 5: Connect event handlers to buttons

Finally, we need to connect the on_button_click method to the button clicks. Add the following code to your script:

    def on_kv_post(self, *args):
        for button in self.children:
            if isinstance(button, Button):
                button.bind(on_press=self.on_button_click)

Step 6: Run the application

To run the application, we need to create an instance of the Calculator class and run it using the run method of the App class. Add the following code to your script:

class CalculatorApp(App):
    def build(self):
        return Calculator()

if __name__ == '__main__':
    CalculatorApp().run()

That’s it! You have now created a basic calculator using Kivy in Python. You can run the script and test the calculator by clicking on the buttons to perform calculations. Feel free to customize the calculator further by adding new features or improving the user interface. Happy coding!

0 0 votes
Article Rating
6 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@kyriosnox
1 month ago

Can you provide the source code?

@sayhag_126
1 month ago

don't forgot cols: 1 in line 7

@faraheadz
1 month ago

thats so cool do you just use
on_press: the symbol on button will be added to the screen and then converted into symbol and calculations will run?

@faraheadz
1 month ago

eyoooooo whattt

@vi_k
1 month ago

Can you not make the buttons with loops or anything?

@insanerawneck3663
1 month ago

Best bhaiya ji