Python 如何将动画保存为gif并同时显示?

Python 如何将动画保存为gif并同时显示?,python,animation,matplotlib,imagemagick,Python,Animation,Matplotlib,Imagemagick,我编写了一个生成并显示matplotlib动画的代码。我还可以将动画保存为gif格式 但是,当我按顺序执行这两个操作时(首先保存gif,然后显示动画,因为plt.show()是一个阻塞调用,所以显示的动画不会从头开始;它似乎是gif保存例程首先使用的 我的想法是使用plt.show()在窗口中显示动画,并将相同的动画作为gif保存到磁盘(在动画之前,或者最好在动画期间)。我曾尝试使用线程或创建新图形来解决此问题,但我无法成功-显示的动画总是通过保存例程进行修改。此外,将plt.show放入线程也

我编写了一个生成并显示
matplotlib
动画的代码。我还可以将动画保存为gif格式

但是,当我按顺序执行这两个操作时(首先保存gif,然后显示动画,因为
plt.show()
是一个阻塞调用,所以显示的动画不会从头开始;它似乎是gif保存例程首先使用的

我的想法是使用
plt.show()
在窗口中显示动画,并将相同的动画作为gif保存到磁盘(在动画之前,或者最好在动画期间)。我曾尝试使用线程或创建新图形来解决此问题,但我无法成功-显示的动画总是通过保存例程进行修改。此外,将
plt.show
放入线程也不起作用(因为我认为它可以处理到屏幕的绘图,所以它需要位于主线程中)

以下是我使用的代码:

import matplotlib.pyplot as plt
from matplotlib import animation
from visualizer import visualize
import updater


def run(k, update_func=updater.uniform,
        steps=1000, vis_steps=50,
        alpha_init=0.3, alpha_const=100, alpha_speed=0.95,
        diameter_init=3, diameter_const=1, diameter_speed=1,
        xlim=(-1, 1), ylim=(-1, 1),
        points_style='ro', lines_style='b-',
        save_as_gif=False):

    fig = plt.figure()
    ax = fig.add_subplot(111, xlim=xlim, ylim=ylim)

    global curr_alpha, curr_diameter, points, lines

    points, = ax.plot([], [], points_style)
    lines, = ax.plot([], [], lines_style)

    curr_alpha = alpha_init
    curr_diameter = diameter_init

    def update_attributes(i):
        global curr_alpha, curr_diameter

        if i % alpha_const == 0:
            curr_alpha *= alpha_speed
        if i % diameter_const == 0:
            curr_diameter *= diameter_speed

    def init():
        lines.set_data([], [])
        points.set_data([], [])

    def loop(i):
        for j in range(vis_steps):
            update_func(k, curr_alpha=curr_alpha, curr_diameter=curr_diameter)
            update_attributes(i * vis_steps + j)
        visualize(k, points, lines)
        return points, lines

    anim = animation.FuncAnimation(fig, loop, init_func=init, frames=steps // vis_steps, interval=1, repeat=False)

    if save_as_gif:
        anim.save('gifs/%s.gif' % save_as_gif, writer='imagemagick')

    plt.show()