简体   繁体   English

python matplotlib使用按钮事件添加和删除文本

[英]python matplotlib add and remove text to figure using button events

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. 我正在尝试在调用button_press_event时将文本添加到鼠标指针位置的图形中,并在调用button_release_event时将其删除。 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()

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称为self.txt ,为了方便起见,我在这里使用global:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM