2016-03-02 44 views
1

我有以下代碼示例。當我按下按鈕時,顏色會改變。但只有在我將鼠標移動一點後。我可以以某種方式直接調用繪圖函數嗎?手動調用matplotlib的繪圖

import matplotlib.pyplot as plt 
from matplotlib.widgets import Button 

def toggle(_): 
    button.status ^= True 

    color = [0, 1, 0] if button.status else [1, 0, 0] 
    button.color = color 
    button.hovercolor = color 

    # Stuff that doesn't work... 
    plt.draw() 
    button.canvas.draw() 
    plt.gcf().canvas.draw() 


button = Button(plt.axes([.1, .1, .8, .8]), 'Press me') 
button.status = True 
button.on_clicked(toggle) 

plt.show() 

回答

1

我相信有一個「官方」的方式做你想做的事,但這裏是模擬鼠標移動事件將觸發重繪一個黑客。在toggle()末添加button.canvas.motion_notify_event(0,0),使您的代碼如下所示:

import matplotlib.pyplot as plt 
from matplotlib.widgets import Button 

def toggle(_): 
    button.status ^= True 

    color = [0, 1, 0] if button.status else [1, 0, 0] 
    button.color = color 
    button.hovercolor = color 

    button.canvas.motion_notify_event(0,0) 

button = Button(plt.axes([.1, .1, .8, .8]), 'Press me') 
button.status = True 
button.on_clicked(toggle) 

plt.show() 
+0

感謝,這項工作圍繞做的伎倆。 –