mpl_connect needs to be called just once to connect the event to event handler. It will start listening to click event until you disconnect. And you can use
fig.canvas.mpl_disconnect(cid)
to disconnect the event hook.
What you want to do is something like:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10,10)
y = x**2
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y)
coords = []
def onclick(event):
global ix, iy
ix, iy = event.xdata, event.ydata
print 'x = %d, y = %d'%(
ix, iy)
global coords
coords.append((ix, iy))
if len(coords) == 2:
fig.canvas.mpl_disconnect(cid)
return coords
cid = fig.canvas.mpl_connect('button_press_event', onclick)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…