Python | Loan calculator using Tkinter

Prerequisite : Tkinter Introduction

Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter outputs the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task.

To create a tkinter :

  1. Importing the module – tkinter
  2. Create the main window (container)
  3. Add any number of widgets to the main window
  4. Apply the event Trigger on the widgets.

Let’s see how to create a loan calculator using Python GUI library Tkiner. The calculator will be capable of calculating the total amount and monthly payment based on loan amount, period an interest rate.

Step #1: Create a main window.

filter_none

edit
close

play_arrow

link
brightness_4
code

def __init__(self):
    # Create a window
    window = Tk() 
    window.title("Loan Calculator") # Set title
 
    # create the input boxes.
    Label(window, text = "Annual Interest Rate").grid(row = 1,
                                       column = 1, sticky = W)
    Label(window, text = "Number of Years").grid(row = 2,
                                  column = 1, sticky = W)
    Label(window, text = "Loan Amount").grid(row = 3,
                              column = 1, sticky = W)
    Label(window, text = "Monthly Payment").grid(row = 4,
                                  column = 1, sticky = W)
    Label(window, text = "Total Payment").grid(row = 5,
                                column = 1, sticky = W)
 
    # for taking inputs
    self.annualInterestRateVar = StringVar()    
    Entry(window, textvariable = self.annualInterestRateVar,
                 justify = RIGHT).grid(row = 1, column = 2)
 
    self.numberOfYearsVar = StringVar()
    Entry(window, textvariable = self.numberOfYearsVar,
            justify = RIGHT).grid(row = 2, column = 2)
 
    self.loanAmountVar = StringVar()
    Entry(window, textvariable = self.loanAmountVar,
         justify = RIGHT).grid(row = 3, column = 2)
 
    self.monthlyPaymentVar = StringVar()
    lblMonthlyPayment = Label(window, textvariable = 
                self.monthlyPaymentVar).grid(row = 4,
                column = 2, sticky = E)
 
    self.totalPaymentVar = StringVar()
    lblTotalPayment = Label(window, textvariable =
                self.totalPaymentVar).grid(row = 5,
                column = 2, sticky = E)
      
    # create the button
    btComputePayment = Button(window, text = "Compute Payment",
                           command = self.computePayment).grid(
                               row = 6, column = 2, sticky = E) 
    # Create an event loop
    window.mainloop() 

chevron_right


 
Step #2: Adding functionality.

filter_none

edit
close

play_arrow

link
brightness_4
code

def computePayment(self):
    # compute the total payment.
    monthlyPayment = self.getMonthlyPayment(float(self.loanAmountVar.get()),
                    float(self.annualInterestRateVar.get()) / 1200,
                    int(self.numberOfYearsVar.get()))
 
    self.monthlyPaymentVar.set(format(monthlyPayment, '10.2f'))
    totalPayment = float(self.monthlyPaymentVar.get()) * 12 \
                           * int(self.numberOfYearsVar.get())
    self.totalPaymentVar.set(format(totalPayment, '10.2f'))
 
# compute the monthly payment.
def getMonthlyPayment(self, loanAmount, monthlyInterestRate, numberOfYears): 
    monthlyPayment = loanAmount * monthlyInterestRate /
                    (1- 1 / (1 + monthlyInterestRate) **
                    (numberOfYears * 12))
 
    return monthlyPayment;

chevron_right


 
Step #3: Complete program

filter_none

edit
close

play_arrow

link
brightness_4
code

# Import tkinter
from tkinter import *
class LoanCalculator:
  
    def __init__(self):
  
        window = Tk() # Create a window
        window.title("Loan Calculator") # Set title
        # create the input boxes.
        Label(window, text = "Annual Interest Rate").grid(row = 1,
                                          column = 1, sticky = W)
        Label(window, text = "Number of Years").grid(row = 2,
                                      column = 1, sticky = W)
        Label(window, text = "Loan Amount").grid(row = 3,
                                  column = 1, sticky = W)
        Label(window, text = "Monthly Payment").grid(row = 4,
                                      column = 1, sticky = W)
        Label(window, text = "Total Payment").grid(row = 5,
                                    column = 1, sticky = W)
  
        # for taking inputs
        self.annualInterestRateVar = StringVar() 
        Entry(window, textvariable = self.annualInterestRateVar,
                     justify = RIGHT).grid(row = 1, column = 2)
        self.numberOfYearsVar = StringVar()
  
        Entry(window, textvariable = self.numberOfYearsVar,
                 justify = RIGHT).grid(row = 2, column = 2)
        self.loanAmountVar = StringVar()
  
        Entry(window, textvariable = self.loanAmountVar,
              justify = RIGHT).grid(row = 3, column = 2)
        self.monthlyPaymentVar = StringVar()
        lblMonthlyPayment = Label(window, textvariable = 
                           self.monthlyPaymentVar).grid(row = 4,
                           column = 2, sticky = E)
  
        self.totalPaymentVar = StringVar()
        lblTotalPayment = Label(window, textvariable = 
                       self.totalPaymentVar).grid(row = 5,
                       column = 2, sticky = E)
          
        # create the button
        btComputePayment = Button(window, text = "Compute Payment",
                                  command = self.computePayment).grid(
                                  row = 6, column = 2, sticky = E) 
        window.mainloop() # Create an event loop
  
  
    # compute the total payment.
    def computePayment(self):
                  
        monthlyPayment = self.getMonthlyPayment(
        float(self.loanAmountVar.get()),
        float(self.annualInterestRateVar.get()) / 1200,
        int(self.numberOfYearsVar.get()))
  
        self.monthlyPaymentVar.set(format(monthlyPayment, '10.2f'))
        totalPayment = float(self.monthlyPaymentVar.get()) * 12 \
                                * int(self.numberOfYearsVar.get())
  
        self.totalPaymentVar.set(format(totalPayment, '10.2f'))
  
    def getMonthlyPayment(self, loanAmount, monthlyInterestRate, numberOfYears): 
        # compute the monthly payment.
        monthlyPayment = loanAmount * monthlyInterestRate / (1
        - 1 / (1 + monthlyInterestRate) ** (numberOfYears * 12))
        return monthlyPayment;
        root = Tk() # create the widget
  
 # call the class to run the program.
LoanCalculator()

chevron_right


Output:

Code Explanation:

  • tkinter module contains the tk toolkit. Here in this example, we are importing the whole module of tkinter in the firstline. Next, We are creating a user-defined Class named LoanCalculator which holds it’s own data member and member functions.
  • def__init__(self) is a special method in Python Class. It is a constructor of a Python class, then we create a window using Tk(). The label function creates a display box to take input and use grid method to give it a table like structure.

Why we used sticky argument?
By default, widgets are created in the center, using sticky arguments we can change it. It takes 4 values: N, S, E, W. i.e. North, East, South, West.

  • Then we create some object named self.annualInterestRateVar, self.numberOfYearsVar, self.loanAmountVar, self.monthlyPaymentVar, self.totalPaymentVar and for the first 3 object we take the input using entry() function.
  • Then we create the button namely compute payment, when you click the button it calls the compute payment function which belongs to the class loan calculator. Using mainloop function we run our application program.
  • Create a function computepayment() inside the class. Here we store our inputs of the object in some variables, to simplify our mathematical calculation.
  • In the next step, we create another function named getMonthlyPayment() inside the class. After getting the required inputs it computes the monthly payment using the simple mathematical function given in the program.
  • Now root=Tk() means to initialize tkinter , we have to create a widget which is a window. Note that root widget must be created before any other widget.


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.