2009-12-27 97 views
5

我對python非常陌生。我正在嘗試編寫一個程序,它將在(x,y)處單擊鼠標,將它移動到(a,b),然後等待鼠標下方的顏色爲特定顏色,讓我們說#fff。當它是那種顏色時,它再次點擊然後重複。模擬鼠標點擊/檢測Python中光標下的顏色

我找不到一個很好的與鼠標有關的python API。

+1

你可以找到一些信息點擊這裏:http://stackoverflow.com/questions/1181464/controlling-mouse-with-python – snw 2009-12-27 21:56:16

回答

6

用於模擬鼠標事件的API取決於您的平臺。我不知道任何跨平臺的解決方案。

在Windows上,您可以通過ctypes訪問Win32 API。見mouse_event on MSDN。您可能也有興趣pywinauto

爲了獲得鼠標下的顏色,您需要鼠標位置。見GetCursorPos on MSDN。那麼如果你的應用有一個API來獲取這個位置的顏色,你可以使用它。如果沒有,您可以嘗試抓住光標周圍的一小部分屏幕,並使用PIL獲取該區域中每個像素的顏色。我認爲PIL屏幕截圖僅適用於Windows平臺,但我不確定。

我使用下面的功能類似的需要:

def grab_main_color(self, rect, max_colors=256): 
    """returns a tuple with the RGB value of the most present color in the given rect""" 
    img=ImageGrab.grab(rect) 
    colors = img.getcolors(max_colors) 
    max_occurence, most_present = 0, 0 
    try: 
     for c in colors: 
      if c[0] > max_occurence: 
       (max_occurence, most_present) = c 
     return most_present 
    except TypeError: 
     raise Exception("Too many colors in the given rect") 
-1

,如果你使用的是Windows,那麼,對於這種事情,你真的想嘗試autohotkey。它不是python,但它是在Windows機器上做這種事情的非常強大的。用戶社區也非常有幫助。看看他們的「尋求幫助」論壇。