Sai A
Updated date Feb 07, 2024
In this blog, we will learn how to create a simple calculator with a graphical user interface (GUI) using Python. This blog covers two methods: one using Tkinter, a built-in GUI toolkit, and another using PyQt5, Python bindings for the Qt framework.

Introduction:

In today's world, programming has become an essential skill, enabling us to automate tasks and create useful tools. Python, with its simplicity and versatility, is an excellent choice for beginners and experienced developers alike. In this blog, we will learn the process of creating a simple calculator with a graphical user interface (GUI) using Python

Method 1: Using Tkinter

Tkinter is a standard GUI toolkit for Python. It's easy to use and comes pre-installed with Python, making it a convenient choice for building graphical applications.

``````import tkinter as tk

def calculate():
try:
result.set(eval(expression.get()))
except:
result.set("Error")

root = tk.Tk()
root.title("Simple Calculator")

expression = tk.StringVar()
result = tk.StringVar()

entry = tk.Entry(root, textvariable=expression)

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

for (text, row, column) in buttons:
button = tk.Button(root, text=text, command=lambda t=text: expression.set(expression.get() + t))

result_label = tk.Label(root, textvariable=result)
result_label.grid(row=5, column=0, columnspan=4)

root.mainloop()
``````

Output:

The program will display a simple GUI with a text entry field for inputting expressions and buttons for digits, operators, and the equal sign. Upon clicking the equal sign (=), the result of the expression will be calculated and displayed below the input field.

• We import the tkinter module and create an instance of the Tk class to create the main window.
• We define a function `calculate()` to evaluate the expression entered by the user using the `eval()` function. If an error occurs during evaluation, such as division by zero, we set the result to "Error".
• We create StringVar objects to store the expression entered by the user and the result of the calculation.
• We create an Entry widget to display the expression entered by the user.
• We create buttons for digits, operators, and the equal sign using a list comprehension and grid them in the main window.
• We create a Label widget to display the result of the calculation.

Method 2: Using PyQT5

PyQt5 is a set of Python bindings for the Qt application framework, widely used for creating cross-platform GUI applications.

``````import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLineEdit, QPushButton, QLabel

class Calculator(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Simple Calculator")
self.expression = QLineEdit()
self.result = QLabel()
self.setup_ui()

def setup_ui(self):
layout = QVBoxLayout()

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

for row in buttons:
row_layout = QVBoxLayout()
for text in row:
button = QPushButton(text)
button.clicked.connect(lambda _, t=text: self.expression.setText(self.expression.text() + t))

self.setLayout(layout)

self.expression.returnPressed.connect(self.calculate)

def calculate(self):
try:
result = eval(self.expression.text())
self.result.setText(str(result))
except:
self.result.setText("Error")

if __name__ == "__main__":
app = QApplication(sys.argv)
calculator = Calculator()
calculator.show()
sys.exit(app.exec_())
``````

Output:

The program will display a GUI with a text entry field for inputting expressions and buttons for digits, operators, and the equal sign. Upon clicking the equal sign (=), the result of the expression will be calculated and displayed below the input field.

• We import necessary modules from PyQt5 and define a class Calculator that inherits from QWidget.
• In the constructor, we set the window title and create QLineEdit and QLabel objects to handle the expression input and display the result, respectively.
• We define a method setup_ui() to create and arrange the widgets using a QVBoxLayout.
• We create buttons for digits, operators, and the equal sign using nested loops and connect their clicked signals to lambda functions that update the expression text.
• We connect the returnPressed signal of the expression QLineEdit to the calculate method.
• We define the calculate method to evaluate the expression entered by the user using the eval() function. If an error occurs during evaluation, we display "Error" in the result label.

Conclusion:

In this blog, we have explored two methods for creating a simple calculator with a graphical user interface using Python. The first method utilizes Tkinter, a built-in GUI toolkit, while the second method employs PyQt5, a set of Python bindings for the Qt framework. Both methods provide an easy way to build a practical application that allows users to perform basic arithmetic operations.