2017-06-23 292 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