29 Jul 2023

Developing a Simple Calculator App with Python and PyQt

In this blog, we will explore how to develop a simple calculator application using the Python programming language and the PyQt framework. PyQt is a powerful toolkit for creating graphical user interfaces (GUIs) and is widely used for developing desktop applications. By the end of this tutorial, you will have a functional calculator app that can perform basic arithmetic operations.

Prerequisites

To follow along with this tutorial, you should have a basic understanding of Python programming and have Python installed on your machine. Additionally, you will need to install the PyQt5 package, which can be easily done using pip, the package installer for Python.

Setting up the Development Environment

Before we start coding, let's make sure we have all the necessary tools and packages installed. Follow these steps:

Install Python 

Download and install the latest version of Python from the official Python website (https://www.python.org). Make sure to select the appropriate version for your operating system.

Install PyQt5 

Open a terminal or command prompt and run the following command to install PyQt5:

pip install PyQt5

Creating the GUI Layout

Now that we have our development environment set up, let's start building the calculator's graphical user interface using PyQt. Import the necessary modules:

from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QLineEdit, QPushButton, QGridLayout
from PyQt5.QtCore import Qt

Create the main window:

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Simple Calculator")
        self.setFixedSize(300, 300)

Create a central widget and set a layout:

central_widget = QWidget(self)
    self.setCentralWidget(central_widget)
    layout = QVBoxLayout(central_widget)

Create a line edit widget to display the calculator's input and results:

self.display = QLineEdit()
    self.display.setFixedHeight(35)
    self.display.setAlignment(Qt.AlignRight)
    layout.addWidget(self.display)
 

<!DOCTYPE html>
<html lang="en">
<head>
<style></style>
</head>
<body></body>
<script></script>
</html>

Create a grid layout for the buttons:

buttons_layout = QGridLayout()
    layout.addLayout(buttons_layout)

Adding Buttons and Functionality

In this step, we will add buttons to the calculator interface and implement their functionality. Create a dictionary to map the button labels to their respective positions in the grid layout:

buttons = {
               "7": (0, 0),
               "8": (0, 1),
               "9": (0, 2),
               "/": (0, 3),
               "4": (1, 0),
               "5": (1, 1),
               "6": (1, 2),
               "*": (1, 3),
               "1": (2, 0),
               "2": (2, 1),
               "3": (2, 2),
               "-": (2, 3),
               "0": (3, 0),
               "C": (3, 1),
               "=": (3, 2),
               "+": (3, 3),
           }

Iterate over the buttons dictionary to create buttons and connect their signals to appropriate slots:

for button_text, position in buttons.items():
               button = QPushButton(button_text)
               button.setFixedSize(50, 50)
               buttons_layout.addWidget(button, *position)
               button.clicked.connect(self.handle_button_click)

Implement the button click handler slot to update the display based on the button clicked:

def handle_button_click(self):
           button = self.sender()
           if button:
               text = button.text()
               if text == "=":
                   self.calculate_result()
               elif text == "C":
                   self.clear_display()
               else:
                   self.display.setText(self.display.text() + text)

Implement the calculate_result and clear_display methods:

def calculate_result(self):
           try:
               result = eval(self.display.text())
               self.display.setText(str(result))
           except Exception as e:
               self.display.setText("Error")

       def clear_display(self):
           self.display.setText("")

Running the Calculator App

Now that we have completed the development of our calculator app, let's run it and see it in action. Add the following code at the end of your script to create an instance of the  QApplication  and  MainWindow classes, and run the application:

if __name__ == "__main__":
       app = QApplication([])
       window = MainWindow()
       window.show()
       app.exec_()

Save the file with a .py extension (e.g., calculator.py) and run it using the Python interpreter:

python calculator.py

Conclusion

Congratulations! You have successfully developed a simple calculator application using Python and the PyQt framework. We explored how to create a GUI layout, add buttons, and implement their functionality. Feel free to enhance the calculator app by adding additional features, error handling, or improving the user interface. With PyQt, you can create a wide range of powerful and visually appealing desktop applications. Happy coding!

You may also like

Developing a Python App for Generating Random Passwords

In this blog, we explore the development of a Python application tha...

Continue reading

PyQt Desktop Applications: Cross-Platform GUI Development

PyQt is a Python library that provides a set of bindings for the Qt ...

Continue reading

Gui Programming in Python Building Desktop Applications with Python

Python Gui - Get GUI programming in Python. we provide developers wi...

Continue reading