如何在动画结束时自动关闭图形界面?

3

我正在尝试使用Python和Matplotlib通过animation.FuncAnimation()显示一个基本动画。这个动画是非循环的,由预定义数量的固定帧组成,并以一些固定间隔进行播放。它只会运行一次。

下面是单个随机帧应该如何显示的样子:random frame

动画可以正常运行,但调用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)
  1. 有没有人能展示一下用Python实现这个的方法?
  2. 我是不是做错了什么?
2个回答

4
也许您想使用动画功能来决定何时关闭图形。
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()

0

在你的动画函数内部使用plt.close()
例如,如果你最后绘制的一帧是iFrame = 9
那么:

if iFrame == 9:
    plt.close()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接