Lab Exercise 8 (Two Number Calculator in PyQT)
Lab Exercise 8 (Two Number Calculator in PyQT)
PyQT
Creating a lab exercise for building a two-number calculator using PyQt involves
providing a hands-on task for learners to create a simple calculator application in
Python with a graphical user interface. In this exercise, learners will build a basic
calculator that can perform addition, subtraction, multiplication, and division
operations on two numbers entered by the user. Here's a step-by-step lab exercise:
Objective: Create a PyQt application with a graphical user interface for performing
arithmetic operations on two numbers.
Requirements:
Instructions:
In this lab exercise, learners will create a two-number calculator application using
PyQt. Follow the steps below:
Create a Python script, e.g., calculator.py, and add the following code to create a
basic PyQt application:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout,
QHBoxLayout, QLineEdit, QPushButton, QLabel
class CalculatorApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# Create input fields
self.num1_input = QLineEdit(self)
self.num2_input = QLineEdit(self)
# Set up layouts
input_layout = QVBoxLayout()
input_layout.addWidget(self.num1_input)
input_layout.addWidget(self.num2_input)
button_layout = QVBoxLayout()
button_layout.addWidget(self.add_button)
button_layout.addWidget(self.subtract_button)
button_layout.addWidget(self.multiply_button)
button_layout.addWidget(self.divide_button)
main_layout = QHBoxLayout()
main_layout.addLayout(input_layout)
main_layout.addLayout(button_layout)
main_layout.addWidget(self.result_label)
self.setLayout(main_layout)
# Connect button clicks to functions
self.add_button.clicked.connect(self.add)
self.subtract_button.clicked.connect(self.subtract)
self.multiply_button.clicked.connect(self.multiply)
self.divide_button.clicked.connect(self.divide)
def add(self):
num1 = float(self.num1_input.text())
num2 = float(self.num2_input.text())
result = num1 + num2
self.result_label.setText(f'Result: {result}')
def subtract(self):
num1 = float(self.num1_input.text())
num2 = float(self.num2_input.text())
result = num1 - num2
self.result_label.setText(f'Result: {result}')
def multiply(self):
num1 = float(self.num1_input.text())
num2 = float(self.num2_input.text())
result = num1 * num2
self.result_label.setText(f'Result: {result}')
def divide(self):
num1 = float(self.num1_input.text())
num2 = float(self.num2_input.text())
if num2 != 0:
result = num1 / num2
self.result_label.setText(f'Result: {result}')
else:
self.result_label.setText('Error: Division by zero')
if __name__ == '__main__':
app = QApplication(sys.argv)
window = CalculatorApp()
window.setWindowTitle('Two-Number Calculator')
window.show()
sys.exit(app.exec_())