你遇到的错误 AttributeError: 'AxesSubplot' object has no attribute 'canvas'
通常是因为在matplotlib的某些版本中,AxesSubplot
对象确实没有 canvas
属性。这个错误通常出现在使用Tkinter作为matplotlib的后端时,尤其是在调整窗口大小后。
这个错误通常是因为matplotlib的某些版本中,AxesSubplot
对象没有 canvas
属性。调整Tkinter窗口大小时,matplotlib的图形更新机制可能会触发这个错误。
以下是一个示例代码,展示如何在Tkinter中使用matplotlib,并确保图形在调整窗口大小后正确更新:
import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
def update_graph():
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 20, 25, 30])
canvas.draw()
root = tk.Tk()
root.title("Matplotlib in Tkinter")
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 20, 25, 30])
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
root.bind("<Configure>", lambda event: canvas.draw())
update_button = tk.Button(root, text="Update Graph", command=update_graph)
update_button.pack(side=tk.BOTTOM)
root.mainloop()
tkinter
创建主窗口。matplotlib.pyplot
创建图形。FigureCanvasTkAgg
将matplotlib图形嵌入到Tkinter窗口中。<Configure>
事件,确保在调整窗口大小后图形能够正确更新。通过这种方式,可以有效避免 AttributeError: 'AxesSubplot' object has no attribute 'canvas'
错误,并确保图形在调整窗口大小后正确更新。
领取专属 10元无门槛券
手把手带您无忧上云