×

Loan Calculator using PyQt5 in Python

In the following tutorial, we will learn how to build a Loan Calculator application using the PyQt5 library in the Python programming language.

So, let's get started.

Introduction to the code:

The heading label for the calculator's name is created, followed by a label and line edit pair for the interest rate. The label specifies what the user must type, while the line edit facilitates text entry. To make a pair for the sum and the year, in the same way, build a calculator push button, design a label that shows the expected monthly payment, and finally, create a label that shows the sum calculated. We started by importing all of the necessary modules into our software. We imported the QtWidgets, QtCore, QtGui, and sys files. The function Object() { [native code] } for initialising our function was then added to a new class that we had built. The window's title, width, and height are then set. We also established the geometry of the window. The widgets were then all displayed. Then, we developed a different function where we would create the heading and different labels as well as set their properties. The headline for the loan calculator was then set, along with its position, geometry, font characteristics, and colour effects. The further steps are included in code explanation part to give a brief on the code.

CODE:

from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui
from PyQt5.QtGui import *
from PyQt5.QtCore import *
  
import sys
class Window(QMainWindow):
    def __init__(self):
        super().__init__()  
        self.setWindowTitle("Python ")  
        self.w_width = 400  
        self.w_height = 500  
        self.setGeometry(100, 100, self.w_width, self.w_height)  
        self.UiComponents()  
        self.show()  
    def UiComponents(self):
        head = QLabel("Loan Calculator", self)  
        head.setGeometry(0, 10, 400, 60)  
        font = QFont('Times', 15)
        font.setBold(True)
        font.setItalic(True)
        font.setUnderline(True)  
        head.setFont(font)  
        head.setAlignment(Qt.AlignCenter)  
        color = QGraphicsColorizeEffect(self)
        color.setColor(Qt.darkCyan)
        head.setGraphicsEffect(color)  
        i_label = QLabel("Annual Interest", self)  
        i_label.setAlignment(Qt.AlignCenter)
        i_label.setGeometry(20, 100, 170, 40)
        i_label.setStyleSheet("QLabel"
                              "{"
                              "border : 2px solid black;"
                              "background : rgba(70, 70, 70, 35);"
                              "}")
        i_label.setFont(QFont('Times', 9))  
        self.rate = QLineEdit(self)  
        onlyInt = QIntValidator()
        self.rate.setValidator(onlyInt)  
        self.rate.setGeometry(200, 100, 180, 40)
        self.rate.setAlignment(Qt.AlignCenter)
        self.rate.setFont(QFont('Times', 9))    
        n_label = QLabel("Years ", self)  
        n_label.setAlignment(Qt.AlignCenter)
        n_label.setGeometry(20, 150, 170, 40)
        n_label.setStyleSheet("QLabel"
                              "{"
                              "border : 2px solid black;"
                              "background : rgba(70, 70, 70, 35);"
                              "}")
        n_label.setFont(QFont('Times', 9))  
        self.years = QLineEdit(self)  
        onlyInt = QIntValidator()
        self.years.setValidator(onlyInt)  
        self.years.setGeometry(200, 150, 180, 40)
        self.years.setAlignment(Qt.AlignCenter)
        self.years.setFont(QFont('Times', 9))  
        a_label = QLabel("Amount", self)  
        a_label.setAlignment(Qt.AlignCenter)
        a_label.setGeometry(20, 200, 170, 40)
        a_label.setStyleSheet("QLabel"
                              "{"
                              "border : 2px solid black;"
                              "background : rgba(70, 70, 70, 35);"
                              "}")
        a_label.setFont(QFont('Times', 9))  
        self.amount = QLineEdit(self)
        onlyInt = QIntValidator()
        self.amount.setValidator(onlyInt)
        self.amount.setGeometry(200, 200, 180, 40)
        self.amount.setAlignment(Qt.AlignCenter)
        self.amount.setFont(QFont('Times', 9))    
        calculate = QPushButton("Compute Payment", self)  
        calculate.setGeometry(125, 270, 150, 40)  
        calculate.clicked.connect(self.calculate_action)  
        self.m_payment = QLabel(self)
        self.m_payment.setAlignment(Qt.AlignCenter)
        self.m_payment.setGeometry(50, 340, 300, 60)
        self.m_payment.setStyleSheet("QLabel"
                                     "{"
                                     "border : 3px solid black;"
                                     "background : white;"
                                     "}")
        self.m_payment.setFont(QFont('Arial', 11))  
        self.y_payment = QLabel(self)  
        self.y_payment.setAlignment(Qt.AlignCenter)
        self.y_payment.setGeometry(50, 410, 300, 60)
        self.y_payment.setStyleSheet("QLabel"
                                     "{"
                                     "border : 3px solid black;"
                                     "background : white;"
                                     "}")
        self.y_payment.setFont(QFont('Arial', 11))  
    def calculate_action(self):
        annualInterestRate = self.rate.text()  
        if len(annualInterestRate) == 0 or annualInterestRate == '0':
            return  
        numberOfYears = self.years.text()  
        if len(numberOfYears) == 0 or numberOfYears == '0':
            return  
        loanAmount = self.amount.text()  
        if len(loanAmount) == 0 or loanAmount == '0':
            return  
        annualInterestRate = int(annualInterestRate)
        numberOfYears = int(numberOfYears)
        loanAmount = int(loanAmount)
  
        monthlyInterestRate = annualInterestRate / 1200  
        monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / (1 + monthlyInterestRate) ** (numberOfYears * 12))  
        monthlyPayment = "{:.2f}".format(monthlyPayment)  
        self.m_payment.setText("Monthly Payment : " + str(monthlyPayment))  
        totalPayment = float(monthlyPayment) * 12 * numberOfYears
        totalPayment = "{:.2f}".format(totalPayment)  
        self.y_payment.setText("Total Payment : " + str(totalPayment))  
App = QApplication(sys.argv)  
window = Window()  
sys.exit(App.exec())

Explanation of code:

Importing all the required modules to get processed, the constructor is used as init function, which is used to inherit the properties. After the function, we used to set the title for the window page, and the page dimensions are applied here, i.e., height and width, using geometry with the calling method. Showing all the widgets may look attractive for the page with a geometry head and using different fonts to set a different color to the head. Then after we create an interesting label by setting properties to the interesting label and then creating a QLineEdit object to get the interest, accepting only the number as input and setting properties to the rate line edit, we create several years label to ask the user for the loan years, interest, and total amount with the QLineEdit object to get the years accepting only number as input the setting properties to the rate line edit. PTO pushes a button to the user, which can conclude the final amount paid by monthly payment and total payment as output.

OUTPUT:

Loan Calculator using PyQt5 in Python

Related Topics

Google Chrome API in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Reverse a sentence In Python

Introduction The built-in reverse() function is not supported by the Python string library. As we know, a Python string is defined as a set of Unicode characters and Python provides various...

4 minutes read.

Python MySQL Update Operation

Python MySQL Update Operation: In this part of tutorial, we will learn that how can we update a table present in SQL database through our Python program. As like SQL,...

4 minutes read.

Palindrome In Python

What is Palindrome? A Palindrome can be defined as the number or a string that resides unchanged when it is reversed. Example: 14341 Output: Yes, this is a Palindrome number Example: RACECAR Output: Yes, this...

2 minutes read.

Python frozenset()

Python frozenset() class The frozenset() class in Python returns a new frozenset object, optionally with elements taken from iterable. Syntax class frozenset([iterable]) Parameter iterable: This parameter represents an iterable object, like list, set, tuple etc. Return This class returns an unchangeable...

1 minute read.

Ternary operators in python

Starting from Python version 2.5, ternary operators are also known as Conditional operators. Using these operators, we can evaluate any problem based on a condition. It is an alternative and...

4 minutes read.

Artificial intelligence mini projects with source code in Python

Project Name: Movie recommendation system A recommendation provides customers with relevant information related to their searches. Before the recommendation system, the most common method of purchasing was to rely on the...

4 minutes read.

Python Function

Python Function A Python function is a reusable, organized block of code that is used to perform the specific task. The functions are the appropriate way to divide an extensive program into a...

7 minutes read.

Python Set intersection_update() method

Python Set intersection_update() method The set.intersection_update() method in Python removes the items that is not present in both sets. It is different from the set.intersection() method, because the intersection()method returns a new set, with only  the common elements...

2 minutes read.

How to make a firewall in Python?

Firewall: The firewall is a network which controls the incoming and outgoing network traffics of a monitor. It blocks the dataset based on the set of rules written in the security...

3 minutes read.

Python String startswith() method

Python String startswith() method The string.startswith() method in Python returns a boolean value ‘True’ if the given string starts with the prefix, otherwise it returns False. Syntax startswith(prefix[, start[, end]]) Parameter prefix: This parameter signifies the value to check. start(optional):...

1 minute read.

Read Text files in Python

In Python, there are many ways to read text files. Before going into the detailed structure of reading a text file, let us understand how reading text files takes place...

4 minutes read.

What is Collaborative Filtering in ML, Python

Introduction Contents recommendation is a useful tactic for almost any specific technology looking to increase interest, but it frequently calls for a lot of user data and perhaps laborious content tagging...

3 minutes read.

What is Python online compiler?

The compiler is a program that is used to scan an entire high-level program (source code) and it translates the scanned program into machine code. Compilers convert .py source code into...

5 minutes read.

How to Install Python

Python Installation Guide Step by Step Installing Python is quite simple and easy. In this tutorial, we will show stepwise procedure to install Python and set up the Python environment in different...

2 minutes read.

Python String capitalize() method

Python String capitalize() method The string.capitalize() method in Python returns a copy of the string with only its first character capitalized. Syntax string.capitalize() Parameter NA Return This function returns a string where the first character is upper...

1 minute read.

How to convert Float to Int in Python?

A float value can be converted to an int via type conversion, an explicit method of transforming an operand to a certain type. But it must be noted that such...

3 minutes read.

Colors in Python

Adding colour to your visualisations will help them come to life. Even if you know the colours you want to use, picking good ones and putting them into practise might...

4 minutes read.

Working with CSV files in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

7 minutes read.

Python Parallel Processing

By performing more jobs concurrently, your software may complete more tasks in a shorter amount of time. These aid in solving major issues. The following subjects will be covered in...

2 minutes read.