在继续之前如何使程序等待鼠标单击

时间:2015-04-04 12:18:37

标签: events python-3.x mouseevent

我正在开发一个程序,该程序应该在两点之间迭代以找到函数的根,给定一定的容差。我的计划是绘制函数,然后通过单击绘图让用户指定两个点。我的问题是,我找不到任何方式来" paus"程序直到指定了两个点,它才会继续。例如,下面的代码在尝试打印coords时为IndexError:list index超出范围[0] [0]

from matplotlib import pyplot as plt    

def on_press(event):
    print('you pressed', event.button, event.xdata, event.ydata)

    global ix, iy 
    ix, iy = event.xdata, event.ydata

    coords = coords.append([ix, iy])

    if len(coords) >1:
        fig.canvas.mpl_disconnect(cid)

def get_clicks(fig):
    cid = fig.canvas.mpl_connect('button_press_event', on_press)

fig = plt.figure()
ax = fig.add_subplot(111)
plt.show()

coords = []

get_clicks(fig)

print(coords[0])

我想要做的是让代码等待" get_clicks(图)"直到两次点击,然后继续其余的代码。

更新

现在代码如下:

def bisec(a,b,tol):

    print("Hi there!")
    return a,b,mid

def on_press(event):
    print('you pressed', event.button, event.xdata, event.ydata) 

    global ix, iy 
    ix, iy = event.xdata, event.ydata

    if len(coords)<=1:
        global coords
        coords.append([ix, iy])

    if len(coords) >1:
        #fig.canvas.mpl_disconnect(cid)
        print(coords)
        bisec(coords[0][0], coords[1][0], 10)

def get_clicks(fig):
    global cid    
    cid = fig.canvas.mpl_connect('button_press_event', on_press)

fig = plt.figure()
ax = fig.add_subplot(111)

coords = []

get_clicks(fig)

plt.show()

所有这一切的目的是在提供2个坐标时调用bisec,这似乎是目前的结果,非常出色!

1 个答案:

答案 0 :(得分:0)

plt.show 应该在最后一行之前。

coords应该被宣布为全球性的。 和     coords = coords.append([ix,iy]) 应该被替换     coords.append([ix,iy])

关于你的上一个问题,是的,这是可能的。 一般的想法是将代码“放在”内部:

if len(coords) >1:

例如:

if len(coords) >1:
    do_what_I_mean(coords)

如果你真的想写:     fig.canvas.mpl_disconnect(CID) 你应该小心确保:

1)cid是一个全局变量 (最简单的方法:不要让函数获得点击,只需在脚本中编写其内容)

2)并在on_press函数中声明为

相关问题