针对单个事件多次调用选取器事件处理程序

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

在我的 Matplotlib 绘图中,我创建了一些 Circle 艺术家,当单击其中一个时,应该会导致一些信息出现在注释中。我的基本代码可以正常工作,只是我看到即使仅单击一次艺术家,也会发生对处理程序的多次调用。通常,我会尝试使用 Python 调试器来调试它,但它在 Matplotlib 事件循环中不起作用。

此事件的处理程序代码如下。 Artists 参数是一个字典,由艺术家键入并保存数据结构作为其值。这是要放入注释中的信息。

def on_pick(event, artists):
    artist = event.artist
    print(f"pick event, {artist} class {artist.__class__}")
    if artist in artists:
        x = artist.center[0]
        y = artist.center[1]
        a = plt.annotate(f"{artists[artist].getX()}", xy=(x,y), xycoords='data')
        artist.axes.figure.canvas.draw_idle()
        print("done")
    else:
        print("on_pick: artist not found")

每个艺术家的 picker 属性都设置为 True,并且 on_pick 函数被安装为 pick 事件的处理程序。当我运行程序时,会创建绘图,然后单击其中一个圆圈。我确实看到注释出现,如预期的那样,但随后我得到了处理程序的第二次或更多调用,如此处所示。

pick event, Circle(xy=(0.427338, 0.431087), radius=0.00287205) class <class 'matplotlib.patches.Circle'>
done
pick event, Circle(xy=(0.427338, 0.431087), radius=0.00287205) class <class 'matplotlib.patches.Circle'>
on_pick: artist not found

前两行是正确的,而后两行来自意外的第二次调用。我也很困惑为什么没有找到该艺术家,因为它与第一次调用时完全相同。

对可能发生的事情有什么想法吗?

python matplotlib events picker
1个回答
0
投票

以下内容无法重现,请提供可重现的示例。

import matplotlib.pyplot as plt
from matplotlib.patches import Circle

fig, ax = plt.subplots()

circle1 = Circle((0, 0), 0.6, color="blue", fill=False)
circle2 = Circle((1, 1), 0.9, color="red", fill=False)

circle1.set_picker(True)
circle2.set_picker(True)

ax.add_patch(circle1)
ax.add_patch(circle2)

def on_pick(event):
    print(f"Clicked on {event.artist}")

fig.canvas.mpl_connect("pick_event", on_pick)

ax.set_xlim(-1, 2)
ax.set_ylim(-1, 2)
ax.set_aspect("equal")

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