python - matplotlib 事件的退出递归
问题描述
我有一个带有button_press_event
. 在侦听器内部,我用来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)
解决方案
你可以使用一个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()
推荐阅读
- typescript - Vuex:未知的动作类型
- javascript - 来自完整字符串的 Cloud Firestore 查询数组
- c# - 如果 WaitOne() 无论如何都会阻塞,那么套接字编程中的异步 Accept() 有什么意义?查看示例
- javascript - 如何正确使用 json-2-csv 节点模块?
- angular - 角度验证与 HTML 验证不同步
- c# - C# / MongoDB - 将枚举字典键序列化为字符串
- python - 将 Dataframe 转换为特定的字典?
- javascript - Is it possible to run 2 threads on javascript?
- sql - 您如何连接 Google Bigquery 中的一系列查询?
- ios - Quantized Sequence using AudioKit