Python 在tkinter窗口中绘制数据
我试图在tkinter窗口中绘制熊猫数据帧。基本上就是我想要实现的:当用户单击graph按钮时,tkinter窗口中会出现一个包含年份和值的图形。但由于某种奇怪的原因,我得到了一个属性错误Python 在tkinter窗口中绘制数据,python,pandas,tkinter,Python,Pandas,Tkinter,我试图在tkinter窗口中绘制熊猫数据帧。基本上就是我想要实现的:当用户单击graph按钮时,tkinter窗口中会出现一个包含年份和值的图形。但由于某种奇怪的原因,我得到了一个属性错误AttributeError:'AxesSubplot'对象没有属性'set\u canvas' “ 知道为什么会这样吗 plotting.py文件: import matplotlib import pandas as pd matplotlib.use("TkAgg") import matplotlib.
AttributeError:'AxesSubplot'对象没有属性'set\u canvas'
“
知道为什么会这样吗
plotting.py文件:
import matplotlib
import pandas as pd
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
fig, ax = plt.subplots()
def plotGraph(self):
data2 = {'Year': [1920, 1930, 1940, 1950, 1960, 1970, 1980, 1990, 2000, 2010],
'Value': [9.8, 12, 8, 7.2, 6.9, 7, 6.5, 6.2, 5.5, 6.3]
}
df2 = pd.DataFrame(data2, columns=['Year', 'Value'])
df2 = df2[['Year', 'Value']].groupby('Year').sum()
yLabelText = "Value"
ax.set_xlabel('Years')
ax.set_ylabel(yLabelText)
fig = plt.figure(figsize=(12, 10), dpi=80)
ax1 = fig.add_subplot(111)
datas = df2.plot(ax=ax1,color ='orange')
ax.get_yaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
fig.tight_layout()
canvas = FigureCanvasTkAgg(datas, self)
canvas.show()
canvas.get_tk_widget().pack(side=self.BOTTOM, fill=self.BOTH, expand=True)
和主界面文件:
try:
import Tkinter as tk
except:
import tkinter as tk
import plotting as pyt
class GetInterfaceValues():
def __init__(self):
self.root = tk.Tk()
self.totalValue = tk.StringVar()
self.root.geometry('500x200')
self.plotGraphButton = tk.Button(self.root, text='plot the kegs values', command=self.plot)
self.plotGraphButton.pack()
self.root.mainloop()
def plot(self):
pyt.plotGraph(self.root)
app = GetInterfaceValues()
您将错误的对象传递到
图CAVASTKAGG
设置为figureCastKagg(figure,master=None,resize\u callback=None)
,因此您需要传递fig
,而不是数据,如下所示:
def plotGraph(self):
...
canvas = FigureCanvasTkAgg(fig, self)
canvas.draw()
canvas.get_tk_widget().pack(side="bottom", fill="both", expand=True)
另外,在将tkinter
与matplotlib
组合时,应该使用Figure
而不是pyplot
。有关示例,请参见。mate。感谢您的回复和解释。如果我删除canvas.show()并将其替换为canvas.draw(),那么您的代码可以工作。你能更新你的答案吗?我会接受这个答案。再次感谢你,伙计