python matplotlib使用按钮事件在图上添加和删除文本 [英] python matplotlib add and remove text to figure using button events
本文介绍了python matplotlib使用按钮事件在图上添加和删除文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在调用 button_press_event 时将文本添加到鼠标指针位置的图形中,并在调用 button_release_event 时将其删除.我已经成功添加了文本,但无法删除它.这是我使用的部分代码:
I'm trying to add text to a graph at the location of the mouse pointer when button_press_event is called and remove it when button_release_event is called. I have successfully added the text but I can not get it to erase. Here is part of the code I used:
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()
推荐答案
假设你应该在一个类中使用它并且将下面的 txt
引用为 self.txt
我为方便起见,请在此处使用 global:
Assuming you should use it in a class and refer to the following txt
as self.txt
I use global here for sake of ease:
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()
这篇关于python matplotlib使用按钮事件在图上添加和删除文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文