Python Matplotlib事件选择器-类内

Python Matplotlib事件选择器-类内,python,events,matplotlib,picker,Python,Events,Matplotlib,Picker,我试图将python文档中显示的事件选择器示例插入到一个类中 代码是这样的 import numpy as np import matplotlib.pyplot as plt class Test: def __init__(self,line): self.line = line self.cidpress = self.line.figure.canvas.mpl_connect('button_press_event', self.onpic

我试图将python文档中显示的事件选择器示例插入到一个类中

代码是这样的

import numpy as np
import matplotlib.pyplot as plt


class Test:
    def __init__(self,line):
        self.line = line
        self.cidpress = self.line.figure.canvas.mpl_connect('button_press_event', self.onpick)

    def onpick(self, event):
        thisline = event.artist
        xdata = thisline.get_xdata()
        ydata = thisline.get_ydata()
        ind = event.ind
        points = tuple(zip(xdata[ind], ydata[ind]))
        print('onpick points:', points)


fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('click on points')

line, = ax.plot(np.random.rand(10), 'o', picker=5)  # 5 points tolerance
a = Test(line)

plt.show()
但当鼠标点击一个点时,我会遇到这个错误

AttributeError: 'MouseEvent' object has no attribute 'artist'
这可能是什么原因? 当不在类中时,代码可以完美地工作


非常感谢

我怀疑代码是否在类之外工作。您在这里面临的问题是,您使用的是一个
'button\u press\u event'
,它没有
artist
属性。无论是在类内还是类外,这都不会改变

  • 如果要使用
    event.artist
    ,则需要使用
    “pick_event”
    。这将显示在matplotlib页面上的中

  • 如果要使用
    “按钮”\u press\u event'
    ,则不能使用
    event.artist
    ,而是需要通过查询某个艺术家是否包含事件来查找已单击的元素,例如
    If line.contains(event)[0]:…
    。例如,见本问题:


谢谢@ImportanceOfBeingErnest。工作起来很有魅力。真不敢相信我花了一整天在这上面。