Building a GUI Desktop Calculator Using PyQt

Building a GUI Desktop Calculator Using PyQt

7 mins read299 Views Comment
Updated on May 15, 2023 01:32 IST

Python is the most commonly used programming language across the world. It is an object-oriented, interpreted, and general-purpose programming language. It can be used to make web applications, system automation, machine learning, deep learning, data analysis, etc. There are many libraries and toolkits provided by Python for GUI applications; PyQt is one of them. Using PyQt, one can easily develop interactive desktop applications.

2023_05_Understanding-Break-Statement-in-C-69.jpg

The demand for GUI desktop applications is increasing day by day. An electronic machine used to perform complex arithmetic calculations is known as a calculator. In this article, we will create a full-fledged interactive GUI Desktop Calculator Using PyQt.

Table of Contents

What is PyQt?

Qt is a famous C++ library that develops GUI applications. These applications are compatible with almost all operating systems, Linux, Windows, Android, iOS, etc. PyQt is the Python binding of the Qt widget toolkit. PyQt is a free software and cross-platform framework. Along with PyQt comes PyQt Designer, which acts as a graphical user interface. One can make GUI Desktop Calculator Using PyQT or Python programming language.

Explore:

Operating system courses free Python courses
free Linux courses programming courses

Feature of PyQt

PyQt has a good collection of classes and modules. At an estimation, PyQt contains more than six hundred classes, each with unique features. 

  • Using PyQt, one can develop cross-platform GUI applications.
  • PyQt is also compatible with databases like SQL.
  • PyQt can also be used for XML processing.
  • PyQt also helps with networking.

Combining these features, PyQt can develop standalone, advanced, and interactive GUI applications. 

Versioning in PyQt

PyQt is available in two versions:

  • PyQt4
  • PyQt5

The main difference between both versions is that PyQt5 has binding for the 5.x version of the Qt framework, whereas PyQt4 has binding for both 4.x and 5.x versions. Hence, PyQt5 is not backward compatible.

How to install PyQt5 on Ubuntu/Linux?

Let us discuss the steps involved in downloading and installing PyQt5 on Ubuntu OS.

  • First, check whether Python 3 is available on your device. For this, use the command
    python3 -V
  • If you get the result, then continue to the next step; otherwise, install Python 3 first.
  • Now install Python pip using command, sudo apt install python3-pip
  • You can check the version of pip using, pip3 -V
  • Here comes the last step, use command sudo pip3 install PyQt5 to install PyQt5 on your system

So PyQt5 has been successfully installed on your system; now it’s time to use PyQt5 to create a sample GUI, followed by the desktop calculator.

Sample GUI application using PyQt5

Let us create an application to get more familiar with PyQt5. We will be developing a sample GUI application that has text written over it.

 
import sys
# importing QtWidgets class modules
from PyQt5.QtWidgets import *
def window():
app = QApplication(sys.argv)
wid = QWidget()
Lab = QLabel(wid)
# set the content to be displayed
Lab.setText("Hello World! I can use PyQt!!")
# set the geometry of application
wid.setGeometry(100, 200, 400, 100)
# move application
Lab.move(50, 20)
# set the title
wid.setWindowTitle("PyQt5")
wid.show()
# start the app
sys.exit(app.exec_())
if __name__ == '__main__':
window()
Copy code

Output:

2023_05_image-41.jpg

Explanation:

In the above application, we imported the QtWidgets module to use the different widgets and labels provided by it.
Lab.setText() is used to set the content that will be displayed on the application screen. wid.setGeometry() is used to set the size and position of the window.
wid.setWindowTitle() is used for setting the title of the application.

Building a GUI Desktop Calculator Using PyQT

A lot of things about PyQt have been discussed until now; we even created a sample application. Now we move to the actual topic of creating an interactive desktop calculator.

This process can be divided into two subdivisions:

Steps for GUI implementation

1. The first step is to create a label with the desired shape. Display all numbers and the output section on it.
2. The font size should be adequate and align the text of the label to the right.
3. Push buttons should be present, numbering from 0-9. Their geometrical shapes should be in perfect sequence.
4. Along with numbers, create push buttons for addition, subtraction, multiplication, and division.
5. The equal button should be highlighted with bright colours to make it more appealing.

Steps for Backend Implementation

1. Functionality or actions should be given to each push button, like for the addition button, its functionality should be to add the numbers.
2. Proper label text should be added to each push button.
3. The action of each button should be like when the button is pressed, then the label text of the button should be appended to the current value present in the window.
4. The action defined for equal to button will be to start try except block.
5. Inside the try block, it should evaluate the label text and display the result on the output screen.
6. And inside except the block, show error as “Wrong Input”.
7. The action of the delete button is to remove the last character present on the output window, and similarly for the clear button is, to set the whole screen text to blank.

Implementation of GUI Desktop Calculator 

 
# Python program to create a GUI Desktop Calculator
# using Python and PyQt5
# import the required libraries
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
Copy code

Step 1: Import all the modules which will be further needed like sys, PyQt5.QtGui etc. 

 
class Window(QMainWindow):
def __init__(self):
super().__init__()
# setting the title of application window
self.setWindowTitle("Python GUI Calculator")
# setting the geometry of application window
self.setGeometry(105, 100, 360, 350)
# calling the function
self.UiComponents()
# displaying all the present widgets
self.show()
Copy code

Step 2: Next, set the title and dimensions of the application window. A call is made to UiComponents() in order to display all widgets.

 
def UiComponents(self):
# creating a new label
self.label = QLabel(self)
# setting the position of the label
self.label.setGeometry(10, 5, 350, 70)
# creating another label having multiple line
self.label.setWordWrap(True)
# Setting the styles to the style sheet to the label
self.label.setStyleSheet("QLabel"
"{"
"border : 50px solidBlack;"
"background : white ; "
"}")
# Adjusting the alignments of the different labels
self.label.setAlignment(Qt.AlignRight)
# setting the label font style
self.label.setFont(QFont('Arial', 14))
Copy code

Step 3: Here is the implementation of the Ui Components function, that is used for creating label elements and styling them. 

 
# Adding the numerical buttons on the application screen
# creating a new push button "1"
push01 = QPushButton("1", self)
# setting the geometry
push01.setGeometry(10, 150, 80, 40)
# creating a new push button "2"
push02 = QPushButton("2", self)
# setting the geometry
push02.setGeometry(100, 150, 80, 40)
# creating a new push button "3"
push03 = QPushButton("3", self)
# setting the geometry
push03.setGeometry(190, 150, 80, 40)
# creating a new push button "4"
push04 = QPushButton("4", self)
# setting the geometry
push04.setGeometry(10, 200, 80, 40)
# creating a new push button "5"
push05 = QPushButton("5", self)
# setting the geometry
push05.setGeometry(100, 200, 80, 40)
# creating a new push button "6"
push06 = QPushButton("6", self)
# setting the geometry
push06.setGeometry(190, 200, 80, 40)
# creating a new push button "7"
push07 = QPushButton("7", self)
# setting the geometry
push07.setGeometry(10, 250, 80, 40)
# creating a new push button "8"
push08 = QPushButton("8", self)
# setting the geometry
push08.setGeometry(100, 250, 80, 40)
# creating a new push button "9"
push09 = QPushButton("9", self)
# setting the geometry
push09.setGeometry(190, 250, 80, 40)
# creating a new push button "0"
push00 = QPushButton("0", self)
# setting the geometry
push00.setGeometry(10, 300, 80, 40)
Copy code

Step 4: Now, we have created all numeric push buttons from 0-9 and set their shape and size. 

 
# Creation and introduction of the operator push button
# creating a new push button for "=" operator
push_equalsTo = QPushButton("=", self)
# setting the geometry
push_equalsTo.setGeometry(280, 300, 80, 40)
# Adding colour effect to "=" button
clr_effect = QGraphicsColorizeEffect()
clr_effect.setColor(Qt.blue)
push_equalsTo.setGraphicsEffect(clr_effect)
# creating a new push button for "+" operator
push_addition = QPushButton("+", self)
# setting the geometry
push_addition.setGeometry(280, 250, 80, 40)
# creating a new push button for "-" operator
push_subtract = QPushButton("-", self)
# setting the geometry
push_subtract.setGeometry(280, 200, 80, 40)
# creating a new push button for "*" operator
push_multiply = QPushButton("*", self)
# setting the geometry
push_multiply.setGeometry(280, 150, 80, 40)
# creating a new push button for "/" operator
push_divide = QPushButton("/", self)
# setting the geometry
push_divide.setGeometry(190, 300, 80, 40)
# creating a new push button for "." operator
push_point = QPushButton(".", self)
# setting the geometry
push_point.setGeometry(100, 300, 80, 40)
# creating a clear button
push_clr = QPushButton("Clear", self)
push_clr.setGeometry(10, 100, 200, 40)
# creating a delete button
push_delete = QPushButton("Del", self)
push_delete.setGeometry(215, 100, 145, 40)
Copy code

Step 5: Now, we have created the push buttons for all arithmetic operators like =, *, /, etc. and set their shape and size. A delete and clear button is also added, along with an equal to button. Special emphasis is given on the “equal to” button.

 
# Adding respective actions to all push buttons created
push_subtract.clicked.connect(self.action_subtract)
push_equalsTo.clicked.connect(self.action_equalsTo)
push00.clicked.connect(self.action0)
push01.clicked.connect(self.action001)
push02.clicked.connect(self.action02)
push03.clicked.connect(self.action03)
push04.clicked.connect(self.action04)
push05.clicked.connect(self.action05)
push06.clicked.connect(self.action06)
push07.clicked.connect(self.action07)
push08.clicked.connect(self.action08)
push09.clicked.connect(self.action09)
push_divide.clicked.connect(self.action_divide)
push_multiply.clicked.connect(self.action_multiply)
push_addition.clicked.connect(self.action_addition)
push_point.clicked.connect(self.action_point)
push_clr.clicked.connect(self.action_clear)
push_delete.clicked.connect(self.action_delete)
Copy code

Step 6: Actions have been applied to all the push buttons in the programme by calling event functions.

 
def action_equalsTo(self):
# getting the label text
equation = self.label.text()
try:
# evaluating the solution
sol = eval(equation)
# setting a new text for the label
self.label.setText(str(sol))
except:
# setting a new text for the label
self.label.setText("Wrong Input")
def action_addition(self):
# appending the text of the label
text = self.label.text()
self.label.setText(text + " + ")
def action_subtract(self):
# appending the text of the label
text = self.label.text()
self.label.setText(text + " - ")
def action_divide(self):
# appending the text of the label
text = self.label.text()
self.label.setText(text + " / ")
def action_multiply(self):
# appending the text of the label
text = self.label.text()
self.label.setText(text + " * ")
def action_point(self):
# appending the text of the label
text = self.label.text()
self.label.setText(text + ".")
def action00(self):
# appending the text of the label
text = self.label.text()
self.label.setText(text + "0")
def action01(self):
# appending the text of the label
text = self.label.text()
self.label.setText(text + "1")
def action02(self):
# appending the text of the label
text = self.label.text()
self.label.setText(text + "2")
def action03(self):
# appending the text of the label
text = self.label.text()
self.label.setText(text + "3")
def action04(self):
# appending the text of the label
text = self.label.text()
self.label.setText(text + "4")
def action05(self):
# appending the text of the label
text = self.label.text()
self.label.setText(text + "5")
def action06(self):
# appending the text of the label
text = self.label.text()
self.label.setText(text + "6")
def action07(self):
# appending the text of the label
text = self.label.text()
self.label.setText(text + "7")
def action08(self):
# appending the text of the label
text = self.label.text()
self.label.setText(text + "8")
def action09(self):
# appending the text of the label
text = self.label.text()
self.label.setText(text + "9")
Copy code

Step 7: Here is the implementation of all event-calling functions. On calling, functions proceed in such a way that text will be added, subtracted, etc., when the next number is pressed. The result of the operation is stored temporarily in a variable and will be shown in the application window once = button is pressed.

 
def action_clear(self):
# clear the text of the label
self.label.setText("")
def action_delete(self):
# clear only a single character
text = self.label.text()
print(text[:len(text) - 1])
self.label.setText(text[:len(text) - 1])
Copy code

Step 8: Here is the implementation of all event-calling functions for the clear and delete button. 

 
# creating the PyQt5 application
root = QApplication(sys.argv)
# creating a Window instance
window = Window()
# executing the application
sys.exit(root.exec())
Copy code

Step 9: Finally, we will create a PyQt5 application by making an instance of Windows and executing the code.

Output:

2023_05_image-41.jpg
2023_05_image-42.jpg
2023_05_image-42.jpg

Contributed by: Vansh Gaur

FAQs

Is Python a dynamically typed language?

Yes, Python is a dynamically typed language. In a dynamically typed language, variable type checking takes place at execution time, unlike in a statically typed language. Examples are Python, Javascript, etc.

Elaborate GUI.

GUI is an abbreviation for Graphical User Interface. GUI acts as a digital interface. A GUI is specially designed to increase the interactivity of users by providing them with images, icons, menus, themes, etc. rather than text-only screens.

Name the various GUI libraries in Python.

Tkinter, PyQt5, PyGUI, wxPython, Kivy and PySimpleGUI.

What is PyQt? Name the language in which PyQt is written.

PyQt is a Python cross-platform GUI library. Currently, PyQt is one of the most famous and powerful GUI libraries. It provides an interactive user interface. PyQt is a mix of C++ and Python.

Is PyQt compatible with Mac OS?

Using PyQt, one can make cross-platform desktop applications that are compatible with most of the popular operating systems like Windows, Ubuntu, Mac Os, etc.

How to install PyQt on Linux and Mac OS?

Below are the commands to install PyQt on Linux and Mac: Linux - sudo apt install python3-pyqt5 Mac - brew install pyqt

What are the different versions of PyQt?

PyQt has two versions, PyQt4 and PyQt5. Also, PyQt5 is not backward-compatible.

How many types of classes are there in PyQt?

PyQt has a good collection of classes and modules. PyQt classes is of QtGui, QtCore, QtSql, QtXml, QtSvg, QtNetwork and QtMultimedia types.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio