我是Matplotlib的新手。最近,我正在练习它,并希望创建一个类似于Matlab的数字应用程序。但是,在早期阶段遇到了夫妻麻烦。这是我经过修改和简化的代码(不影响我的意图):
import tkinter as tk
import matplotlib.backends.backend_tkagg as tkagg
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
class AppWindow(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, 'Activity Labeling Tool')
app_window = tk.Frame(self)
app_window.grid(row = 0, column = 0, sticky = 'nsew')
# app_window.pack(side = 'top', fill = 'both', expand = True)
app_window.grid_rowconfigure(0, weight = 1)
app_window.grid_columnconfigure(0, weight = 1)
self.frames = {}
frame = MainPage(app_window, self)
self.frames[MainPage] = frame
frame.grid(row = 0, column = 0, sticky = "nsew")
self.show_frame(MainPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise() # raise the frame to the front
class MainPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
fig = Figure(figsize = (8, 4.5), dpi = 120)
ax = fig.add_subplot(111)
ax.plot([1,2,3,4,5,6,7,8,9],[2,1,1,1,1,1,1,1,2])
canvas = tkagg.FigureCanvasTkAgg(fig, self)
canvas.get_tk_widget().grid(row = 1, column = 0)
canvas.draw()
frame_toolbar = tk.Frame(self)
frame_toolbar.grid(row = 3, sticky = tk.W)
toolbar = tkagg.NavigationToolbar2Tk(canvas, frame_toolbar)
toolbar.update()
canvas._tkcanvas.grid(row = 1, column = 0)
def load_csv():
ax.clear() # Want to clear the fig, but not activated here
'''
load file
'''
btn_load_file = tk.Button(self, text = 'Load File', command = load_csv)
btn_load_file.grid(row = 0, column = 0)
app = AppWindow()
app.mainloop()
我的目的是在导入CSV文件之前清除图形,以确保图形干净。但是,当按下我的加载文件按钮时,.clear()
方法未正确激活。
我试图将ax
传递给load_csv函数,但仍得到相同的结果。而且我非常确定.clear()
在def
之外可以正常工作。在Matplotlib甚至Python方面我有什么想念的吗?
感谢您查看我的问题。任何建议将不胜感激。再次谢谢你!