Python:如何使用matplotlib.canvas在鼠标单击时获取坐标
我正在写一个类来处理图像。在这个类中,我想定义一个方法,允许我返回鼠标点击的坐标。我可以将坐标作为属性获取,但如果调用该方法返回坐标,则会得到一个空元组 代码如下:Python:如何使用matplotlib.canvas在鼠标单击时获取坐标,python,matplotlib,coordinates,Python,Matplotlib,Coordinates,我正在写一个类来处理图像。在这个类中,我想定义一个方法,允许我返回鼠标点击的坐标。我可以将坐标作为属性获取,但如果调用该方法返回坐标,则会得到一个空元组 代码如下: import cv2 import matplotlib.pyplot as plt class TestClass(): def __init__(self): self.fname = 'image.jpg' self.img = cv2.imread(self.fname)
import cv2
import matplotlib.pyplot as plt
class TestClass():
def __init__(self):
self.fname = 'image.jpg'
self.img = cv2.imread(self.fname)
self.point = ()
def getCoord(self):
fig = plt.figure()
ax = fig.add_subplot(111)
plt.imshow(self.img)
cid = fig.canvas.mpl_connect('button_press_event', self.__onclick__)
return self.point
def __onclick__(self,click):
self.point = (click.xdata,click.ydata)
return self.point
只要我在
getCoord
中的mpl\u connect
之后插入plt.show()
,您的代码对我有效:
def getCoord(self):
fig = plt.figure()
ax = fig.add_subplot(111)
plt.imshow(self.img)
cid = fig.canvas.mpl_connect('button_press_event', self.__onclick__)
plt.show()
return self.point
非常感谢你。这对我也有好处。现在我同意我的教授的观点,他曾经说过“调试自己的代码比调试别人的代码更难”。省略了这句话,让我花了好几个小时试图找到bug。谢谢