2011-04-08 34 views
3

我試圖在調用button_press_event時將文本添加到鼠標指針的位置處的圖形,並在調用button_release_event時將其刪除。我已經成功添加了文本,但我無法清除它。下面是我使用的代碼的一部分:python matplotlib添加和刪除文本使用按鈕事件的圖形

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

回答

9

假設你應該在課堂上使用它,請參閱下面的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() 
相關問題