1

Suppose I to write a function get_coords which prompts the user for some input coordinates. One way to do this would be as follows:

def get_coords():
    coords_string = input("What are your coordinates? (x,y)")
    coords = tuple(coords_string)
    return coords

However, I'd like to use this using a GUI rather than the command line. I've tried the following:

def onclick(event):
    return (event.x, event.y)

def get_coords_from_figure():
    fig = plt.figure()
    plt.axvline(x=0.5)      # Placeholder data
    plt.show(block=False)
    cid = fig.canvas.mpl_connect('button_press_event', onclick)

However, using coords = get_coords_from_figure() results in a coords variable which is empty, unlike if I use coords = get_coords(), because the input function waits for user input.

How could I prompt a user for input using a GUI?

1
  • If you put a print inside onclick, will that print be printed? Commented Aug 10, 2016 at 17:44

1 Answer 1

1
import matplotlib.pyplot as plt

def get_coords_from_figure():
    ev = None
    def onclick(event):
        nonlocal ev
        ev = event

    fig, ax = plt.subplots()
    ax.axvline(x=0.5)      # Placeholder data
    cid = fig.canvas.mpl_connect('button_press_event', onclick)

    plt.show(block=True)
    return (ev.xdata, ev.ydata) if ev is not None else None
    # return (ev.x, ev.y) if ev is not None else None

You need to actually return something your function (and block on the show).

If you need to have this function return, then define a class with on_click as a member method which mutates the objects state and then consult the object when you need to know the location.

Sign up to request clarification or add additional context in comments.

1 Comment

The only thing is that the nonlocal keyword is only available in Python 3. How would I make this work in Python 2?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.