2017-06-23 293 views
1

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

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?") 

我可以使用动画对象来重放动画或做另一个plt.show()吗?

预先感谢你的答案 与亲切的问候, 杰拉德

回答

1

图之后,已经显示一次,它无法显示使用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窗口。要重置动画开始,你会使用

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() 
+0

完美的,我没想到还没有这种方法,但它现在最好的解决方案。谢谢! – Grard