退出matplotlib事件的递归

问题描述 投票:0回答:1

我有一个带有button_press_event的matplotlib小人物。在听众内部,我使用plt.pause来为每次点击制作简短的动画。这工作正常,并且符合预期。但是,如果我在动画结束之前再次单击,则会输入递归,其余动画将在最后播放。如果单击得足够快,您甚至可以到达RecursionError

我需要更改什么,因此单击新键将放弃on_click方法中所有剩余的步骤?

import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.subplots()

ax.set_xlim(0, 10)
ax.set_ylim(0, 10)

xy = np.random.random(2)*10
h1 = ax.plot(xy[0], xy[1], marker='x', color='k')[0]
h2 = ax.plot(xy[0], xy[1], marker='o', color='r')[0]

def on_click(event):
    h1.set_xdata(event.xdata)
    h1.set_ydata(event.ydata)
    for i in range(10):
        h2.set_xdata(event.xdata+np.random.random()-0.5)
        h2.set_ydata(event.ydata+np.random.random()-0.5)
        plt.pause(0.1)

cid_click = fig.canvas.mpl_connect('button_press_event', on_click)

python matplotlib recursion events pause
1个回答
0
投票

您可以使用FuncAnimation。然后确保在开始播放新动画之前停止并删除以前的动画。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()

ax.set_xlim(0, 10)
ax.set_ylim(0, 10)

xy = np.random.random(2)*10
h1 = ax.plot(xy[0], xy[1], marker='x', color='k')[0]
h2 = ax.plot(xy[0], xy[1], marker='o', color='r')[0]

anis = []
def on_click(event):
    h1.set_xdata(event.xdata)
    h1.set_ydata(event.ydata)
    def animate(i):
        h2.set_xdata(event.xdata+np.random.random()-0.5)
        h2.set_ydata(event.ydata+np.random.random()-0.5)
    for ani in anis:
        ani.event_source.stop()
        anis.remove(ani)
        del ani
    anis.append(FuncAnimation(fig, animate, frames=10, repeat=False))
    fig.canvas.draw_idle()

cid_click = fig.canvas.mpl_connect('button_press_event', on_click)

plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.