使用 类 时尝试 运行 在 Tkinter 中实时显示 matplotlib 图。无法解决类型错误

Trying to run live matplotlib graph in Tkinter while using classes. Cannot resolve TypeError

我正在尝试在使用 class 结构的同时在 Tkinter 中获取实时 matplotlib 图。我正在使用此 中的代码,它在 Tkinter 中成功 运行s 了一个 matplotlib 图(不使用 class 结构)。每次我尝试 运行 我更改的代码时,我都会得到

TypeError: __init__ takes exactly 2 arguments (1 given)

我知道以前有人问过这个 TypeError 类型的问题。我尝试使用 但提供的答案没有解决我的问题。

似乎是问题的代码行是:

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()

我不确定你想做什么,但你可能想要这样的东西:

root = Tk.Tk()
app = Window(root)
ani = animation.FuncAnimation(app.fig, app.animate(),interval=1000, blit=False)
root.mainloop()

这不会完全解决问题,因为 animate 函数也没有参数。

你有很多错误:

正如 Paul Comelius 所说,您必须创建实例

app = Window(root)
ani = animation.FuncAnimation(app.fig, app.animate, interval=1000, blit=False)

-

您必须在 class 中使用 self.fig 才能稍后将其作为 app.fig

-

animation.FuncAnimation 需要回调——这意味着没有 ().
的函数名 在你的代码中它将是 app.animate.

ani = animation.FuncAnimation(app.fig, app.animate, interval=1000, blit=False)

-

完整的工作代码

import Tkinter as Tk
from matplotlib import pyplot as plt
import matplotlib.animation as animation
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

class Window:

    def __init__(self,master):
        frame = Tk.Frame(master)

        self.fig = plt.figure(figsize=(14, 4.5), dpi=100)

        self.ax = self.fig.add_subplot(1,1,1)
        self.ax.set_ylim(0, 100)
        self.line, = self.ax.plot(xar, yar)

        self.canvas = FigureCanvasTkAgg(self.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)

xar = []
yar = []

root = Tk.Tk()
app = Window(root)
ani = animation.FuncAnimation(app.fig, app.animate, interval=1000, blit=False)
root.mainloop()