📜  Python|使用 Tkinter 的贷款计算器

📅  最后修改于: 2022-05-13 01:55:23.733000             🧑  作者: Mango

Python|使用 Tkinter 的贷款计算器

先决条件:Tkinter 介绍

Python为开发 GUI(图形用户界面)提供了多种选择。在所有的 GUI 方法中,Tkinter 是最常用的方法。它是Python随附的 Tk GUI 工具包的标准Python接口。带有 Tkinter 的Python输出创建 GUI 应用程序的最快和最简单的方法。使用 Tkinter 创建 GUI 是一项简单的任务。

创建一个 Tkinter :

  1. 导入模块 – Tkinter
  2. 创建主窗口(容器)
  3. 将任意数量的小部件添加到主窗口
  4. 在小部件上应用事件触发器。

GUI 将如下所示:

让我们看看如何使用Python GUI 库 Tkinter 创建贷款计算器。计算器将能够根据贷款金额、期限和利率计算总金额和每月还款额。
步骤#1:创建主窗口。

Python3
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()


Python3
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;


Python3
# 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()



步骤#2:添加功能。

Python3

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;


步骤#3:完成程序

Python3

# 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()

输出:

代码说明:

  • Tkinter 模块包含 TK工具包。在这个例子中,我们在第一行导入了 Tkinter 的整个模块。接下来,我们将创建一个名为 LoanCalculator 的用户定义类,它拥有自己的数据成员和成员函数。
  • def__init__(self) 是Python类中的一个特殊方法。它是一个Python类的构造函数,然后我们使用 Tk() 创建一个窗口。 label函数创建一个显示框来接受输入,并使用 grid 方法给它一个类似表格的结构。

为什么我们使用粘性参数?
默认情况下,小部件在中心创建,使用粘性参数我们可以更改它。它需要 4 个值:N、S、E、W。即北、东、南、西。

  • 然后我们创建一些名为 self.annualInterestRateVar、self.numberOfYearsVar、self.loanAmountVar、self.monthlyPaymentVar、self.totalPaymentVar 的对象,对于前 3 个对象,我们使用 entry()函数获取输入。
  • 然后我们创建了计算支付按钮,当你点击这个按钮时,它会调用属于类贷款计算器的计算支付函数。使用 mainloop函数我们运行我们的应用程序。
  • 在类中创建一个函数computepayment()。在这里,我们将对象的输入存储在一些变量中,以简化我们的数学计算。
  • 在下一步中,我们在类中创建另一个名为 getMonthlyPayment() 的函数。在获得所需的输入后,它使用程序中给出的简单数学函数计算每月付款。
  • 现在 root=Tk() 意味着初始化tkinter ,我们必须创建一个窗口小部件。请注意,根小部件必须在任何其他小部件之前创建。