2017-04-13 113 views
1

我想暂停我在自己的事件循环中运行的动画。下面是代码的简化版本:暂停matplotlib自定义动画循环

import numpy as np 
import matplotlib.pyplot as plt 
from matplotlib.widgets import Button 
from mpl_toolkits.mplot3d import proj3d 

import time 

def main(): 
    global paused 
    paused = False 

    fig = plt.figure() 
    ax = fig.add_subplot(111, projection='3d') 

    ax.set_ylim(-100, 100) 
    ax.set_xlim(-10, 10) 
    ax.set_zlim(-100, 100) 

    plt.ion() 
    plt.show() 

    def pause_anim(event): 
     global paused 
     paused = not paused 

    pause_ax = fig.add_axes((0.7, 0.03, 0.1, 0.04)) 
    pause_button = Button(pause_ax, 'pause', hovercolor='0.975') 
    pause_button.on_clicked(pause_anim) 

    x = np.arange(-50, 51) 

    line = ax.plot([], [], [], c="r")[0] 

    y_range = list(np.arange(1, 60, 3)) 
    y_len = len(y_range) 
    idx = 0 

    while True: 

     if not paused: 
      idx += 1 
      if idx >= y_len: 
       break 

      y = y_range[idx] 
      z = - x**2 + y - 100 

      line.set_data(x, 0) 
      line.set_3d_properties(z) 

      plt.draw() 
      plt.pause(0.2) 

     else: 
      time.sleep(1) # this stops button events from happening 
      #input("Shoop?") # prompting for input works 
      # I've also tried putting a mutex here 

if __name__ == '__main__': 
    main() 

正如我在代码中提及,我已经试过time.sleepLock,但这些阻止我取消暂停一次,我已经暂停。如何暂停循环而不破坏恢复动画的能力?

回答

1

你可能只是plt.pause取代time.sleep(1)else双组分,就像你也做到了在if -part。

 .... 
     plt.draw() 
     plt.pause(0.2) 
    else: 
     plt.pause(0.2) 

另一种选择是,当然使用matplotlib动画,像FuncAnimation,其具有方法.event_source.stop().event_source.start()。 (如这个问题的两个答案所示:stop/start/pause in python matplotlib animation