将matplotlib图形上的鼠标单击坐标保存到Python中的列表中,并在单击后与图形断开连接

2024-04-25 17:42:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将鼠标左键单击坐标保存到matplotlib图形的列表中。以下是我迄今为止所写的内容:

def onclick(event):
    
    coord = [event.xdata,event.ydata]
    print(coord)
    return coord


def locate():
    
    fig = plt.gcf()
    cid = fig.canvas.mpl_connect('button_press_event',onclick)
    fig.canvas.mpl_disconnect(cid)

正如您可能已经从我的代码中了解到的,我是Python新手。使用上述代码,我无法返回coord。我试图使coord成为global变量,但没有得到结果。
我想在一次鼠标点击后断开与图形的连接,并将坐标保存为列表。 基本上,我希望语句coordinates = locate()将列表保存到变量coordinates。 我在Juypter笔记本上工作

类似的问题:get Coordinates of matplotlib plot figure python with mouse click


Tags: 代码event图形列表matplotlibdeffig鼠标