Python matplotlib 动画重复

Python matplotlib Animation repeat

我使用 matplotlib.animation 和 FuncAnimation 制作了一个动画。 我知道我可以将 repeat 设置为 True/False 来重播动画,但是还有一种方法可以在 FuncAnimation 返回后重播动画吗?

anim = FuncAnimation(fig, update, frames= range(0,nr_samples_for_display), blit=USE_BLITTING, interval=5,repeat=False)

plt.show()
playvideo = messagebox.askyesno("What to do next?", "Play Video again?")

我可以使用 anim 对象重播动画或执行另一个 plt.show() 吗?

提前感谢您的回答 亲切的问候, 杰拉德

图形显示一次后,无法使用plt.show()显示第二次。

一个选项是重新创建图形以再次显示该新图形。

createfig():
    fig = ...
    # plot something
    def update(i):
        #animate
    anim = FuncAnimation(fig, update, ...)

createfig()
plt.show()

while messagebox.askyesno(..):
    createfig()
    plt.show()

重启动画的更好选择可能是将用户对话框集成到 GUI 中。这意味着在动画结束时,您询问用户是否要重播动画,而无需先实际关闭 matplotlib window。要将动画重置为开始,您可以使用

ani.frame_seq = ani.new_frame_seq() 

示例:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import Tkinter
import tkMessageBox

y = np.cumsum(np.random.normal(size=18))
x = np.arange(len(y))

fig, ax=plt.subplots()

line, = ax.plot([],[], color="crimson")

def update(i):
    line.set_data(x[:i],y[:i])
    ax.set_title("Frame {}".format(i))
    ax.relim()
    ax.autoscale_view()
    if i == len(x)-1:
        restart()

ani = animation.FuncAnimation(fig,update, frames=len(x), repeat=False)

def restart():
    root = Tkinter.Tk()
    root.withdraw()
    result = tkMessageBox.askyesno("Restart", "Do you want to restart animation?")
    if result:
        ani.frame_seq = ani.new_frame_seq() 
        ani.event_source.start()
    else:
        plt.close()

plt.show()