我的Tkinter预算应用程序并不总是清除matplotlib图。
我已经创建了一个Tkinter预算应用程序作为一个项目,以改善OOP和类继承。该应用程序接受输入,计算预算,并绘制花钱的位置图。有一个“重置”按钮可以清除输入,有时仅清除图形。我想知道为什么它不一致地清除了情节。另外,我是Tkinter菜鸟,所以如果有人看到我的代码有些愚蠢,可以随意批评它。预先谢谢你。
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,
NavigationToolbar2Tk
from matplotlib.figure import Figure
# create main app area
class Main_App:
def __init__(self, master):
self.master = master
# include a top line
self.title = Label(master, text="Tkinter Budget App")
self.title.config(font=("Courier", 17))
self.title.grid(row=0, columnspan=4, sticky=W+E, pady=(10, 20))
# ask for monthly income
self.income = Label(master, text="Monthly income:")
self.income.config(font=("Courier", 12))
self.income.grid(row=1, column=0, sticky=W, padx=10, pady=20)
# monthly income box
self.income_box = Entry(master, width=15)
self.income_box.grid(row=1, column=1, sticky=E, pady=20)
# ask for rent/mortgage payment
self.housing = Label(master, text="Rent/mortgage payment:")
self.housing.config(font=("Courier", 12))
self.housing.grid(row=2, column=0, sticky=W, padx=10)
# rent/mortgage payment box
self.housing_box = Entry(master, width=15)
self.housing_box.grid(row=2, column=1, sticky=E)
# ask for car payment
self.vehicle = Label(master, text="Car payment:")
self.vehicle.config(font=("Courier", 12))
self.vehicle.grid(row=3, column=0, sticky=W, padx=10)
# car payment box
self.vehicle_box = Entry(master, width=15)
self.vehicle_box.grid(row=3, column=1, sticky=E)
# ask for insurance
self.insurance = Label(master, text="Car/life insurance payment:")
self.insurance.config(font=("Courier", 12))
self.insurance.grid(row=4, column=0, sticky=W, padx=10)
# insurance box
self.insurance_box = Entry(master, width=15)
self.insurance_box.grid(row=4, column=1, sticky=E)
# ask for power
self.power = Label(master, text="Power bill:")
self.power.config(font=("Courier", 12))
self.power.grid(row=5, column=0, sticky=W, padx=10)
# power box
self.power_box = Entry(master, width=15)
self.power_box.grid(row=5, column=1, sticky=E)
# ask for gas (home)
self.gas = Label(master, text="Gas (home) bill:")
self.gas.config(font=("Courier", 12))
self.gas.grid(row=6, column=0, sticky=W, padx=10)
# gas (home) box
self.gas_box = Entry(master, width=15)
self.gas_box.grid(row=6, column=1, sticky=E)
# ask for cable/internet
self.cable_internet = Label(master, text="Cable/internet bill:")
self.cable_internet.config(font=("Courier", 12))
self.cable_internet.grid(row=7, column=0, sticky=W, padx=10)
# cable/internet box
self.cable_internet_box = Entry(master, width=15)
self.cable_internet_box.grid(row=7, column=1, sticky=E)
# ask for groceries
self.groceries = Label(master, text="Groceries bill:")
self.groceries.config(font=("Courier", 12))
self.groceries.grid(row=8, column=0, sticky=W, padx=10)
# groceries box
self.groceries_box = Entry(master, width=15)
self.groceries_box.grid(row=8, column=1, sticky=E)
# ask for gas (vehicle)
self.car_gas = Label(master, text="Gas (vehicle) bill:")
self.car_gas.config(font=("Courier", 12))
self.car_gas.grid(row=9, column=0, sticky=W, padx=10)
# gas (vehicle) box
self.car_gas_box = Entry(master, width=15)
self.car_gas_box.grid(row=9, column=1, sticky=E)
# ask for recreation
self.recreation = Label(master, text="Recreation:")
self.recreation.config(font=("Courier", 12))
self.recreation.grid(row=10, column=0, sticky=W, padx=10)
# recreation box
self.recreation_box = Entry(master, width=15)
self.recreation_box.grid(row=10, column=1, sticky=E)
# ask for other
self.other = Label(master, text="Other:")
self.other.config(font=("Courier", 12))
self.other.grid(row=11, column=0, sticky=W, padx=10)
# recreation box
self.other_box = Entry(master, width=15)
self.other_box.grid(row=11, column=1, sticky=E)
# add a calculate button
self.calculateButton = Button(master, text="Calculate", command=self.calculate, width=12)
self.calculateButton.grid(row=12, column=1, sticky=E, pady=(10, 10))
# add a clear button
self.clearButton = Button(master, text="Reset", command=self.clear_all, width=12)
self.clearButton.grid(row=13, column=1, sticky=E, pady=(10, 10))
# prepare label for money saved per month
self.money_saved_mo = Label(master, text="Monthly possible savings: ")
self.money_saved_mo.config(font=("Courier", 12))
self.money_saved_mo.grid(row=15, column=0, sticky=W, padx=10)
# prepare area for outcome
self.money_saved_mo_num = StringVar()
self.money_saved_mo_num_label = Label(master, textvariable=self.money_saved_mo_num, fg="green", font=("Courier", 12))
self.money_saved_mo_num_label.grid(row=15, column=1, sticky=E)
# prepare label for money saved per year
self.money_saved_yr = Label(master, text="Yearly possible savings: ")
self.money_saved_yr.config(font=("Courier", 12))
self.money_saved_yr.grid(row=16, column=0, sticky=W, padx=10)
# prepare area for outcome
self.money_saved_yr_num = StringVar()
self.money_saved_yr_num_label = Label(master, textvariable=self.money_saved_yr_num, fg="green", font=("Courier", 12))
self.money_saved_yr_num_label.grid(row=16, column=1, sticky=E)
# calculate the money to save
def calculate(self):
income = float(self.income_box.get())
expenses = sum([
float(self.housing_box.get()),
float(self.vehicle_box.get()),
float(self.insurance_box.get()),
float(self.power_box.get()),
float(self.gas_box.get()),
float(self.cable_internet_box.get()),
float(self.groceries_box.get()),
float(self.car_gas_box.get()),
float(self.recreation_box.get()),
float(self.other_box.get())
])
self.money_saved_mo_num.set("${0:0.2f}".format(income - expenses))
self.money_saved_yr_num.set("${0:0.2f}".format(12 * (income - expenses)))
# create bar plot
# define x and y
x = ["Housing", "Vehicle", "Insurance", "Power", "Gas", "Cable", "Groceries", "Gas (car)", "Recreation", "Other"]
y = [float(self.housing_box.get()), float(self.vehicle_box.get()), float(self.insurance_box.get()), float(self.power_box.get()), float(self.gas_box.get()), float(self.cable_internet_box.get()), float(self.groceries_box.get()), float(self.car_gas_box.get()), float(self.recreation_box.get()), float(self.other_box.get())]
# create a figure
self.fig = Figure(figsize=(8, 4)) # size of figure
a = self.fig.add_subplot(111)
a.barh(x, y, color="green") # plot type and color
a.invert_yaxis() # invert the y-axis
# title and axis labels
a.set_title ("Money ($) Spent by Mode", fontsize=12)
a.set_xlabel("Money ($)", fontsize=10)
# draw the plot
canvas = FigureCanvasTkAgg(self.fig, master=self.master)
canvas.get_tk_widget().grid(row=2, rowspan=30, column=2, columnspan=80, padx=20)
canvas.draw()
# clear the inputs, outputs, and plot
def clear_all(self):
# inputs
self.income_box.delete(0, "end")
self.vehicle_box.delete(0, "end")
self.housing_box.delete(0, "end")
self.insurance_box.delete(0, "end")
self.power_box.delete(0, "end")
self.gas_box.delete(0, "end")
self.cable_internet_box.delete(0, "end")
self.groceries_box.delete(0, "end")
self.car_gas_box.delete(0, "end")
self.recreation_box.delete(0, "end")
self.other_box.delete(0, "end")
# outputs
self.money_saved_mo_num.set("")
self.money_saved_yr_num.set("")
# plot
self.fig.clf() # here is where I am trying to clear the plot
# create manu bar
class Menu_Bar(Main_App): # inherit objects from Main_App
def __init__(self, master):
Main_App.__init__(self, master)
self.master = master
# create a menu bar
self.menuBar = Menu(master)
master.config(menu=self.menuBar)
# create file tab
self.fileMenu = Menu(self.menuBar, tearoff=0)
self.menuBar.add_cascade(label="File", menu=self.fileMenu)
# create commands under file
# Reset
self.fileMenu.add_command(label="Reset", command=self.clear_all)
# close
self.fileMenu.add_command(label="Close", command=master.destroy)
# run the app
if __name__=='__main__':
root = Tk()
root.geometry("1225x600")
root.title("Tkinter Budget Application")
app = Main_App(root)
app = Menu_Bar(root) # seems weird to have two of these saved as app
root.mainloop()
我希望在按下“重置”按钮时清除图和输入。