Kurt Peek
Kurt Peek

Reputation: 57451

How to prompt for user input using a Matplotlib GUI rather than a command line prompt

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?

Upvotes: 1

Views: 4232

Answers (1)

tacaswell
tacaswell

Reputation: 87376

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.

Upvotes: 1

Related Questions