Python 如何通过matplotlib中的func停止FuncAnimation?

Python 如何通过matplotlib中的func停止FuncAnimation?,python,animation,matplotlib,Python,Animation,Matplotlib,我编写了一个matplotlib动画程序,如下所示: def animate(frame): observation = env.render() action = RL.choose_action(str(observation)) # TODO action = [random.randint(0, 4) for i in range(ROBOT_NUM)] # TO BE DELETE TODO env.step(action) observatio

我编写了一个matplotlib动画程序,如下所示:

def animate(frame):
    observation = env.render()
    action = RL.choose_action(str(observation)) # TODO
    action = [random.randint(0, 4) for i in range(ROBOT_NUM)] # TO BE DELETE TODO
    env.step(action)
    observation_ = env.render()
    reward = env.reward
    RL.learn(str(observation), action, reward, str(observation_))  # TODO
    for i in range(TARGET_NUM):
        patchs_target[i].center = (env.targets[i].x, env.targets[i].y)
    for i in range(ROBOT_NUM):
        patchs[i].center = (env.robots[i].x, env.robots[i].y)
        patchs_inner[i].center = (env.robots[i].x, env.robots[i].y)
    return patchs + patchs_inner + patchs_target

现在我想通过判断
animate
函数中的条件来停止
animation.FuncAnimation
。例如
如果奖励<10
则停止
animation.FuncAnimation
,但我不知道如何处理它。
或者是否有任何方法可以根据条件停止
animation.FuncAnimation
?不按动画时间。有两个选项:

(1) 使用发电机 为了动态地控制动画,可以使用生成器,只要满足某些条件,生成器就会在while循环中生成新值。这可能如下所示:

reward = 0

def gen():
    global reward
    i = 0
    while reward <= 10:
        i += 1
        yield i

def animate(i):
    global reward
    reward = update(reward)
    some_object[i] = func(reward)
    return some_object

anim = animation.FuncAnimation(fig, animate, frames=gen, repeat = False)

请注意,这两个代码都未经测试,因为问题没有提供测试用例。

我想请您阅读。手头没有可运行的示例,很难提供正确的答案。
reward = 0

def gen():
    global reward
    i = 0
    while reward <= 10:
        i += 1
        yield i

def animate(i):
    global reward
    reward = update(reward)
    some_object[i] = func(reward)
    return some_object

anim = animation.FuncAnimation(fig, animate, frames=gen, repeat = False)
class Anim():
    def __init__(self, fig, **kw):
        self.reward=0
        self.ani = animation.FuncAnimation(fig, self.animate, 
                                           frames=100, repeat = False) 

    def animate(self,i):
        reward = update(reward)
        some_object[i] = func(reward)
        if self.reward > 10:
            self.ani.event_source.stop()
        return some_object