簡體   English   中英

FuncAnimation() 在未分配給變量時不起作用

[英]FuncAnimation() doesn't work when not assigned to a variable

我有以下 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 對象如何知道它已被分配給一個變量?

文檔解釋了它:

[..] 保持對實例對象的引用至關重要。 動畫由一個計時器(通常來自主機 GUI 框架)推進,Animation 對象持有該計時器的唯一引用。 如果您不持有對 Animation 對象的引用,它(以及計時器)將被垃圾收集,這將停止動畫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM