如何从 matplotlib 的 button_press_event 返回值?

use*_*687 5 python matplotlib

我是新来的,也是新来的 python 和 matplotlib 。

我想创建一个代码,允许我从函数定义中获取坐标(event.xdata),以便我以后可以使用该数据。但正如我到目前为止所读到的,一些变量是局部变量(函数内部的变量),其他变量是全局变量(我们“稍后”要使用的变量)。我尝试使用“全局”选项,我也读过这不是最好的,并且它不起作用...解决方案当然可能是从定义的选取函数返回值...问题是我必须创建一个接收函数返回的变量...但由于这是一个事件(不是简单的函数),我不能要求变量接收返回,因为它是绘制绘图后发生的事件。可能应该(?)类似于:

import matplotlib.pyplot as plt
import numpy as np

asd = () #<---- i need to create a global variable before i can return a value in it? 
fig = plt.figure()
def on_key(event):
    print('you pressed', event.key, event.xdata, event.ydata)
    N=event.xdata
    return N in asd #<---- i want to return N into asd

cid = fig.canvas.mpl_connect('key_press_event', on_key)
lines, = plt.plot([1,2,3])
NAAN=on_key(event) #<---- just to try if return alone worked... but on_key is a function which happens in the plot event... so no way to take the info from the return
plt.show()
Run Code Online (Sandbox Code Playgroud)

tac*_*ell 7

您可以使用可变对象和闭包来做到这一点:

mutable_object = {} 
fig = plt.figure()
def on_key(event):
    print('you pressed', event.key, event.xdata, event.ydata)
    N=event.xdata
    mutable_object['key'] = N
Run Code Online (Sandbox Code Playgroud)

然后你可以通过以下方式恢复你的价值

N = mutable_object['key']
Run Code Online (Sandbox Code Playgroud)

使用它,您还可以使用listand来完成此操作append,或者创建您自己的类等。