如何从 button_press_event matplotlib 返回一个值? [英] how to return a value from button_press_event matplotlib?

查看:69
本文介绍了如何从 button_press_event matplotlib 返回一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

im在这里是新的,在python和matplotlib上也是新的.

im new here, as well as new on python and on matplotlib also.

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

I wanted to create a code which allows me to get the coordinates (event.xdata) out from the function define so that i can use that data later. But as ive been able to read so far, some variables are local (the ones inside functions) and others are globals (the ones that we want to use 'later'). I tried with the 'global' option which i also read is not the best, and it didnt worked... The solution might be of course to return the value from the defined picking function... the problem is i have to create a variable who recieves the return fromt he function... but since this is an event (not a simple function) i can not ask a variable to recieve the return, because it is an event which happens after the plot is drawn. The could should(?) be something similar to:

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()

推荐答案

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

You can do this with a mutable object and closures:

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

然后你可以用

N = mutable_object['key']

使用它,您还可以使用 listappend 执行此操作,或创建自己的类等.

Using this you can also do this with a list and append, or create your own class, ect.

这篇关于如何从 button_press_event matplotlib 返回一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆