2015-08-20 45 views
0

我正在處理一些圖像數據,點擊圖像中的不同元素會有幫助。我希望將「shift-click」作爲註冊光標位置的觸發機制。未按Matplotlib正確註冊的按鍵事件

我寫了一個「點擊」功能,做正確的事情。但是,當我嘗試將其升級到「shift-click」時,它根本不起作用。奇怪的是,它使用老版本的Matplotlib(1.1,運行在Linux機器上,我的版本是1.4.2,在Mac上運行,兩個都運行Python 2.7)都能在我的同事的計算機上工作。

任何人有任何想法是怎麼回事?我完全沒有想法。其他可能相關的信息是我最近安裝了Seaborn(然後卸載它)並升級了matplotlib(並試圖降級,但失敗了)

編輯好吧,我想我現在明白了。在開始正常工作之前,換擋必須至少按下並釋放一次。也許有一個解決方法。

import numpy as np 
import matplotlib.pyplot as plt 

def shiftclick(refimage, comment=None, eq=True): 
    class EventHandler: 
     def __init__(self, spotlist): 
      fig.canvas.mpl_connect('button_press_event', self.onpress) 
      fig.canvas.mpl_connect('key_press_event', self.on_key_press) 
      fig.canvas.mpl_connect('key_release_event', self.on_key_release) 
      self.shift_is_held = False 
     def on_key_press(self, event): 
      if event.key == 'shift': 
       self.shift_is_held = True 
     def on_key_release(self, event): 
      if event.key == 'shift': 
       self.shift_is_held = False 
     def onpress(self, event): 
      if event.inaxes!=ax: 
       return 
      if self.shift_is_held: 
       xi, yi = (int(round(n)) for n in (event.xdata, event.ydata)) 
       value = im.get_array()[xi,yi] 
       print xi, yi 
       spotlist.append((xi, yi)) 
    im = plt.imshow(refimage, interpolation='nearest', origin='lower') 

    plt.title('SHIFT-click on locations') 
    fig = plt.gcf() 
    ax = plt.gca() 

    spotlist = [] 
    handler=EventHandler(spotlist) 
    plt.show() 
    return spotlist 


def click(refimage, comment=None): 
    class EventHandler: 
     def __init__(self, spotlist): 
      fig.canvas.mpl_connect('button_press_event', self.onpress) 
     def onpress(self, event): 
      if event.inaxes!=ax: 
       return 
      xi, yi = (int(round(n)) for n in (event.xdata, event.ydata)) 
      value = im.get_array()[xi,yi] 
      print xi, yi 
      spotlist.append((xi, yi)) 
    im = plt.imshow(refimage, interpolation='nearest', origin='lower') 

    fig = plt.gcf() 
    ax = plt.gca() 

    spotlist = [] 
    handler=EventHandler(spotlist) 
    plt.show() 
    return spotlist 

if __name__ == "__main__": 
    a = np.random.random((100, 100)) 
    #this works 
    click(a) 
    #this doesn't work 
    shiftclick(a) 

回答

0

好的,這是問題所在。升級Matplotlib後,MacOSX後端拒絕正確處理事件處理。它忽略了所有的按鍵按下。

使用TKAgg後端解決了問題,只要在嘗試選擇點之前至少按下一次shift鍵即可。這仍然是不可取的。

使用Qt4Agg後端有最好的行爲。只要窗口被選中,它就會正確響應第一個移位按鍵。