【发布时间】:2018-05-05 13:53:55
【问题描述】:
我正在尝试使用类结构在 Tkinter 中获取实时 matplotlib 图。我正在使用来自stackoverflow question 的代码,它在 Tkinter 中成功运行了 matplotlib 图(不使用类结构)。每次我尝试运行我更改的代码时,都会得到一个
TypeError: __init__ takes exactly 2 arguments (1 given)
我知道以前有人问过这个 TypeError 类型的问题。我尝试使用this,但提供的答案并没有解决我的问题。
似乎有问题的代码行是:
ani = animation.FuncAnimation(Window().fig, Window().animate(), interval=1000, blit=Fals
我尝试改变我调用 fig 和 animate 的方式,但似乎没有任何效果。
import Tkinter as Tk
from matplotlib import pyplot as plt
import matplotlib.animation as animation
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
xar = []
yar = []
class Window:
def __init__(self,master):
frame = Tk.Frame(master)
fig = plt.figure(figsize=(14, 4.5), dpi=100)
self.ax = fig.add_subplot(1,1,1)
self.ax.set_ylim(0, 100)
self.line, = self.ax.plot(xar, yar)
self.canvas = FigureCanvasTkAgg(fig,master=master)
self.canvas.show()
self.canvas.get_tk_widget().pack(side='top', fill='both', expand=1)
frame.pack()
def animate(self,i):
yar.append(99-i)
xar.append(i)
self.line.set_data(xar, yar)
self.ax.set_xlim(0, i+1)
root = Tk.Tk()
ani = animation.FuncAnimation(Window().fig, Window().animate(),interval=1000, blit=False)
app = Window(root)
root.mainloop()
【问题讨论】:
-
好吧,您正在调用 WIndow() 构造函数 - 两次 - 它需要一个参数。你什么都没通过。
-
我还尝试在 Window() 类之外定义 fig ,因此我只会调用一次 Window 构造函数,但它不起作用。 ani = animation.FuncAnimation(fig, Window().animate,interval=1000, blit=False)
-
将
fig留在原处。只需创建一次对象,然后访问其方法。看我的回答。
标签: python python-2.7 matplotlib tkinter tkinter-canvas