我正在尝试在调用button_press_event时将文本添加到鼠标指针位置的图形中,并在调用button_release_event时将其删除。我已经成功添加了文本,但我无法将其删除。以下是我使用的代码的一部分:
def onclick(event):
print 'you pressed', event.button, event.xdata, event.ydata
plt.text(event.xdata, event.ydata, 'TESTTEST', fontsize=8)
fig.canvas.draw()
def offclick(event):
print 'you released', event.button, event.xdata, event.ydata
#not sure what to put here
#I tried:
#plt.text(event.xdata, event.ydata, '')
fig.canvas.draw()
fig.canvas.mpl_connect('button_press_event', onclick)
fig.canvas.mpl_connect('button_release_event', offclick)
plt.show()
答案 0 :(得分:10)
假设您应该在课程中使用它,并将以下txt
称为self.txt
我为了方便起见,请使用全局:
txt = None
def onclick(event):
global txt
txt = plt.text(event.xdata, event.ydata, 'TESTTEST', fontsize=8)
fig.canvas.draw()
def offclick(event):
txt.remove()
fig.canvas.draw()
fig.canvas.mpl_connect('button_press_event', onclick)
fig.canvas.mpl_connect('button_release_event', offclick)
plt.show()