如何在python的tkinter框架中导入matplotlib 3D动画?

时间:2018-11-20 09:57:54

标签: python animation matplotlib tkinter 3d

我正在尝试在Tkinter窗口中导入matplotlib 3D动画,但遇到了错误。我的Tkinter窗口有很多帧,我尝试在其中一个帧上绘制动画。最后,我在类init函数中创建所有元素。因此,这是我的代码的简化版本:

from tkinter import *
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import  FigureCanvasTkAgg
from matplotlib.figure import Figure
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as anim
import random

class UI:
    def __init__(self):
        self.back = Frame(master=self.window, width=1200, height=800, bg='white')
        self.rightBack = Frame(master=self.back, width=300, height=800)
        self.rightBack.pack(side='right',padx=2,pady=2)
        self.fig = Figure()
        self.axes = Axes3D(self.fig)

        self.ani = anim.FuncAnimation(self.fig, self.updateDisplay, interval=100, blit=False) #  Creating animation

        self.canvas = FigureCanvasTkAgg(self.fig, master=self.displayBack)
        self.canvas.get_tk_widget().pack(side=TOP,fill=BOTH,expand=True)


        # Starting application
        self.window.mainloop()

    def updateDisplay(self,num):
        self.axes.clear()
        self.axes.plot([0,1,random.random()],[0,1,random.random()],[0,1,random.random()],'o',color='k',markersize='5')

但是当我在python中运行以下代码

self.ani = anim.FuncAnimation(self.fig, self.updateDisplay, interval=100, blit=False)

我收到此错误

File "matplotlib/animation.py", line 1703, in __init__
TimedAnimation.__init__(self, fig, **kwargs)

File "matplotlib/animation.py", line 1465, in __init__
event_source = fig.canvas.new_timer()

AttributeError: 'NoneType' object has no attribute 'new_timer'

所以我认为我理解错误是因为动画需要一个计时器,但我不知道如何解决。有什么帮助吗?先谢谢了

1 个答案:

答案 0 :(得分:0)

动画需要驻留在具有画布的图形中。在您的代码中,仅在动画之后 定义画布。我想如果您反转动画和画布的顺序,它将按预期工作。

# First define the canvas
self.canvas = FigureCanvasTkAgg(self.fig, ...)
# only then define the animation
self.ani = anim.FuncAnimation(self.fig, ...)