未分配给变量的FuncAnimation()不起作用

时间:2019-07-07 15:23:04

标签: python matplotlib

我有以下Python代码段:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig = plt.figure()
ax = fig.add_subplot(111)

x = np.arange(0, 2 * np.pi, 0.01)
line, = ax.plot(x, np.sin(x))


def animate(i):
    line.set_ydata(np.sin(x + i / 10))
    return line,
# note: no anim=animation.FuncAnimation(...) assignment
animation.FuncAnimation(fig, animate)
plt.show()

它不符合我的预期-运行时,它会在图形上显示正弦图,但不会更新。将FuncAnimation()结果分配给变量时,这样做会很困难。为什么? Python对象如何知道它已被分配给变量?

1 个答案:

答案 0 :(得分:0)

The documentation对此进行了解释:

  

[..]至关重要的是保留对实例对象的引用。动画由计时器(通常来自主机GUI框架)推进,Animation对象持有该计时器唯一的引用。如果您没有保留对Animation对象的引用,则该对象(以及计时器)将被垃圾回收,这将停止动画。

相关问题