how to return a value from button_press_event matplotlib?

matplotlib, python

Solution

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

You can then get your value back out with

N = mutable_object['key']

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

Problem

im new here, as well as new on python and on matplotlib also. 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() ```

Original source