Loan Calculator using PyQt5 in Python


Welcome to this thorough article on using PyQt5 in Python to build a Loan Calculator. The PyQt5 library's robust features can be used to provide a straightforward and approachable user interface for our calculator. This post will provide a thorough explanation of how to build such a calculator, along with real-world examples to help make the process more understandable.

Introduction to PyQt5

Cross-platform apps can be made using PyQt5, a set of Python bindings for Qt libraries. It combines the greatest features of Python and Qt and gives developers the freedom to create code in Python while utilising the extensive library of Qt modules. PyQt5 is frequently employed while creating desktop apps.

Introduction to Loan Calculator

With the help of a loan calculator, you can calculate how much money you'll need to repay a loan based on the loan's terms, interest rate, and quantity. By offering a GUI, users may enter these numbers with ease and get the calculated results.

Steps to Create Loan Calculator using PyQt5

The following steps are typical for building a loan calculator with PyQt5 −

  • Installation  Install the PyQt5 library first, if it isn't already. Pip can be used for this:

pip install PyQt5
  • Designing the GUI  This include developing the various GUI components, such as text fields for loan information entry and calculating buttons.

  • Implementing the Logic  On the basis of the user's inputs, define the logic for the loan calculation.

  • Binding the Logic to GUI  Connect the implemented logic to the GUI components so that it will run when the correct GUI components are manipulated.

Examples of Loan Calculator Using PyQt5

Here, we'll show you how to use Python's PyQt5 to build a simple loan calculator.

Example 1: Basic Loan Calculator

In this demonstration, we'll build a straightforward loan calculator with fields for the loan amount, interest rate, and length.

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout
from PyQt5.QtGui import QDoubleValidator
from PyQt5.QtCore import Qt

class LoanCalculator(QWidget):
   def __init__(self):
      super().__init__()

      self.initUI()

   def initUI(self):
      layout = QVBoxLayout()

      self.amountLabel = QLabel("Loan Amount:")
      self.amountLineEdit = QLineEdit()
      self.amountLineEdit.setValidator(QDoubleValidator(0, 1000000, 2))

      self.interestLabel = QLabel("Interest Rate:")
      self.interestLineEdit = QLineEdit()
      self.interestLineEdit.setValidator(QDoubleValidator(0, 100, 2))

      self.termLabel = QLabel("Loan Term (years):")
      self.termLineEdit = QLineEdit()
      self.termLineEdit.setValidator(QDoubleValidator(0, 100, 0))

      self.resultLabel = QLabel("")

      self.calculateButton = QPushButton("Calculate")
      self.calculateButton.clicked.connect(self.calculateLoan)

      layout.addWidget(self.amountLabel)
      layout.addWidget(self.amountLineEdit)
      layout.addWidget(self.interestLabel)
      layout.addWidget(self.interestLineEdit)
      layout.addWidget(self.termLabel)
      layout.addWidget(self.termLineEdit)
      layout.addWidget(self.resultLabel)
      layout.addWidget(self.calculateButton)

      self.setLayout(layout)

   def calculateLoan(self):
      P = float(self.amountLineEdit.text())
      r = float(self.interestLineEdit.text()) / 100 / 12
      n = float(self.termLineEdit.text()) * 12

      M = P * (r * (1 + r) ** n) / ((1 + r) ** n - 1)

      self.resultLabel.setText(f"Monthly payment: {M:.2f}")

def main():
   app = QApplication(sys.argv)

   calculator = LoanCalculator()
   calculator.show()

   sys.exit(app.exec_())

if __name__ == '__main__':
   main()

Based on user input, this PyQt5 programme generates a loan calculator that computes and shows the monthly payment.

The loan calculation logic is implemented by the calculateLoan method, which applies the following formula to determine a loan payment with a set interest rate −

M = P[r(1+r)^n]/[(1+r)^n – 1]

where 

  • Your recurring payment is M.

  • P stands for the principal loan sum.

  • By dividing your yearly interest rate by twelve, you can determine your monthly interest rate, or r.

  • Your monthly loan repayment schedule, or n, is the number of installments you will make.

We will improve our calculator in the following example so that it can handle more difficult cases and produce information that is more in-depth.

Example 2: Advanced Loan Calculator

In this example, we'll add further capabilities to our loan calculator, such as the capability to figure out the total payments over the loan's period.

Note − This advanced example mainly focuses on the new features and assumes that the reader is already familiar with PyQt5.

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout
from PyQt5.QtGui import QDoubleValidator
from PyQt5.QtCore import Qt

class AdvancedLoanCalculator(QWidget):
   def __init__(self):
      super().__init__()

      self.initUI()

   def initUI(self):
      layout = QVBoxLayout()

      self.amountLabel = QLabel("Loan Amount:")
      self.amountLineEdit = QLineEdit()
      self.amountLineEdit.setValidator(QDoubleValidator(0, 1000000, 2))

      self.interestLabel = QLabel("Interest Rate:")
      self.interestLineEdit = QLineEdit()
      self.interestLineEdit.setValidator(QDoubleValidator(0, 100, 2))

      self.termLabel = QLabel("Loan Term (years):")
      self.termLineEdit = QLineEdit()
      self.termLineEdit.setValidator(QDoubleValidator(0, 100, 0))

      self.monthlyPaymentLabel = QLabel("Monthly payment:")
      self.totalRepaymentLabel = QLabel("Total repayment:")

      self.calculateButton = QPushButton("Calculate")
      self.calculateButton.clicked.connect(self.calculateLoan)

      layout.addWidget(self.amountLabel)
      layout.addWidget(self.amountLineEdit)
      layout.addWidget(self.interestLabel)
      layout.addWidget(self.interestLineEdit)
      layout.addWidget(self.termLabel)
      layout.addWidget(self.termLineEdit)
      layout.addWidget(self.monthlyPaymentLabel)
      layout.addWidget(self.totalRepaymentLabel)
      layout.addWidget(self.calculateButton)

      self.setLayout(layout)

   def calculateLoan(self):
      P = float(self.amountLineEdit.text())
      r = float(self.interestLineEdit.text()) / 100 / 12
      n = float(self.termLineEdit.text()) * 12

      M = P * (r * (1 + r) ** n) / ((1 + r) ** n - 1)
      Total = M * n

      self.monthlyPaymentLabel.setText(f"Monthly payment: {M:.2f}")
      self.totalRepaymentLabel.setText(f"Total repayment: {Total:.2f}")

def main():
   app = QApplication(sys.argv)

   calculator = AdvancedLoan

The calculateLoan method is expanded in this application to calculate and display the total repayment over the loan's length as well. This is obtained by merely dividing the total number of payments by the monthly amount.

Conclusion

In this post, we've introduced PyQt5 and shown how to utilise it to build a straightforward but useful Python loan calculator application. We went through the code and talked about how the calculations are done and shown.

You should now be able to implement and use a fundamental loan computation technique, as well as create GUI apps in Python using PyQt5. We hope this article was useful, whether you're a novice trying to learn Python GUI programming or an experienced developer looking to improve your abilities.

As you become more comfortable with PyQt5, we encourage you to explore its more advanced features and use it to create more complex applications. Remember, practice is key when learning a new programming language or library.

Updated on: 18-Jul-2023

190 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements