Python 如何使用Matplotlib GUI而不是命令行提示符提示用户输入

Python 如何使用Matplotlib GUI而不是命令行提示符提示用户输入,python,matplotlib,Python,Matplotlib,假设我要编写一个函数get_coords,它会提示用户输入一些坐标。一种方法是: def get_coords(): coords_string = input("What are your coordinates? (x,y)") coords = tuple(coords_string) return coords 但是,我希望使用GUI而不是命令行来使用它。我尝试了以下方法: def onclick(event): return (event.x, eve

假设我要编写一个函数
get_coords
,它会提示用户输入一些坐标。一种方法是:

def get_coords():
    coords_string = input("What are your coordinates? (x,y)")
    coords = tuple(coords_string)
    return coords
但是,我希望使用GUI而不是命令行来使用它。我尝试了以下方法:

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)
但是,使用
coords=get\u coords\u from\u figure()
会导致
coords
变量为空,这与使用
coords=get\u coords()
不同,因为
input
函数等待用户输入

如何使用GUI提示用户输入

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
您需要实际返回函数中的某些内容(并在节目中阻止)


如果需要返回此函数,请在单击时定义一个带有
的类作为成员方法,该方法会改变对象状态,然后在需要知道位置时查阅对象。

如果在onclick中放置打印,打印出来吗?唯一的问题是,
nonlocal
关键字只在Python 3中可用。如何在Python 2中实现这一点?