我正在尝试使用Python和Matplotlib通过animation.FuncAnimation()
显示一个基本动画。这个动画是非循环的,由预定义数量的固定帧组成,并以一些固定间隔进行播放。它只会运行一次。
动画可以正常运行,但调用plt.show()
之后,图形并不会自动关闭,因为它是一个阻塞调用。
我知道可以通过写入plt.show(block=False)
来将方法plt.show()
变为非阻塞调用,但这并不能完全解决我的问题。我无法从StackOverflow和其他网站上获得任何关于这个事件的信息,以便让我调用plt.close()
。
我正在寻找一种Pythonic的方式来解决这个问题,而不是我的当前解决方案,因为那远非最佳解决方案。这是我的"解决方案":
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
# Animation settings
def animate(frame):
grid_size = [10, 10]
print('frame: {}'.format(frame)) # Debug: May be useful to stop
grid = np.random.randint(low=0, high=256, size=grid_size, dtype=np.uint8)
ax.clear()
ax.imshow(grid, cmap='gray', vmin=0, vmax=255) # Is the range [0, 255] or [0, 255)?
INTERVAL = 100
FRAMES_NUM = 10
anim = animation.FuncAnimation(fig, animate, interval=INTERVAL, frames=FRAMES_NUM, repeat=False)
plt.show(block=False)
plt.pause(float(FRAMES_NUM*INTERVAL)/1000) # Not pythonic
plt.close(fig)
- 有没有人能展示一下用Python实现这个的方法?
- 我是不是做错了什么?