我正在尝试通过 animation.FuncAnimation()
使用 Python 和 Matplotlib 显示基本动画.动画是不重复的,由固定(和预定义)数量的帧组成,帧之间有固定的间隔。它应该运行一次。
动画运行正常,但在调用 plt.show()
后图形不会自动关闭因为这是一个阻塞调用。
我知道 plt.show()
方法可以通过编写 plt.show(block=False)
变成非阻塞调用,但是并不能完全解决我的问题。我无法在 StackOverflow 和其他网站上获得有关图书馆如何处理此 event 左右信息的任何信息,以便让我调用 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)
- 任何人都可以告诉我执行此操作的 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)
grid_size = [10, 10]
grid = np.random.randint(low=0, high=256, size=grid_size, dtype=np.uint8)
im = ax.imshow(grid, cmap='gray', vmin=0, vmax=255)
# Animation settings
def animate(frame):
if frame == FRAMES_NUM:
print(f'{frame} == {FRAMES_NUM}; closing!')
plt.close(fig)
else:
print(f'frame: {frame}') # Debug: May be useful to stop
grid = np.random.randint(low=0, high=256, size=grid_size, dtype=np.uint8)
im.set_array(grid)
INTERVAL = 100
FRAMES_NUM = 10
anim = animation.FuncAnimation(fig, animate, interval=INTERVAL,
frames=FRAMES_NUM+1, repeat=False)
plt.show()
关于python - 如何在动画结束时自动关闭图形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55942672/