×

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

What is Python compiler GDB?

The source code of one programming language is converted into machine code, bytecode, or another programming language by a compiler, a specialised software. A compiler is a tool that converts high-level...

3 minutes read.

PyDev with Python IDE

What is IDE? Integrated Development Environment is the abbreviation of IDE. It is a coding tool that automates code editing, finding errors and testing. IDE combines all the developer tools into...

3 minutes read.

Python Random shuffle( ) method

The shuffle() is used to change the positions of the elements in the mutable sequences. The shuffle( ) function will change the positions of the elements in the sequence of...

3 minutes read.

Difference between Mutable and Immutable Objects

Difference between Mutable and Immutable Objects As we all know that Python is an object-oriented programming language. Object-oriented programming approach is based on the objects and the classes’ stores the data...

4 minutes read.

App Config Python

An XML file called App. Config serves as the document for any programme. In other terms, you can modify any configuration inside of it without going to edit the code...

7 minutes read.

Difference between Yield and Return in Python

Python yield statement The generators are defined by using the yield statement in Python. Generally, it converts a normal Python function into a generator.  The yield statement hauls the function and returns...

3 minutes read.

Python String

Python String Python string is considered as the most popular data type present in Python language. In Python, string data type is the collection of characters, letters, white spaces etc. written...

31 minutes 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.

Python Printf Style Formating

String objects have one special implicit activity: the % administrator (modulo). This is otherwise called the string designing or interjection administrator. Given design % values (where configuration is a string),...

3 minutes read.

How To Install Python In Ubuntu

How To Install Python In Ubuntu Ubuntu is free and open-source software and it is an essential part of the Linux distribution. It is a popular operating system developed by Canonical. If we...

3 minutes read.

Best Database for Python

Database The collection of structured data or information in an organized format in a computer system is known as Database. The data is inserted, deleted, updated, controlled, or manipulated in a...

6 minutes read.

To Do GUI Application using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

Nested List in Python

The list is an inbuilt sequential data type in Python. It is a very useful and frequently used data type. A list can store any number of data items of...

4 minutes read.

Python String rjust() method

Python String rjust() method The string.rjust() method in Python returns a right-justified string of a given minimum width where the padding is done using the specified fillchar (default is a space). It returns...

2 minutes read.

Python Dictionary copy() method

Python Dictionary copy() method The dictionary.copy () method in Python returns a copy of the specified dictionary. Syntax dictionary.copy () Parameter NA Return None Example 1 # Python program explaining # the dictionary.copy() method # initialising the dictionary ...

1 minute read.

Why learn Python?

All things considered, learning python would be extraordinary, it'll acquaint you with the universe of dynamic programming dialects, if you're somebody who has had a semester of involvement with C. Python...

4 minutes read.

Python max() function

Python max() function The max() function in Python returns the largest item in an iterable or the largest of two or more arguments. Syntax max(iterable, *[, key, default])               or max(arg1, arg2, *args[, key])   Parameter arg1, arg2, *args: This...

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.

Python File Handling

What is the file? The file is a collection of data in a single unit. It is used to store information in the non-volatile memory such as hard-disk. Computer programs generally run on the RAM...

7 minutes read.

Python dir() function

Python dir() function The dir() function in Python returns all properties and methods of the specified object, without the values. Syntax dir([object]) Parameter object: This parameter represents the object one wants to see the valid attributes. Return This function...

2 minutes read.