Log*_*man 5 python mouse colors
我是python的新手.我正在尝试编写一个程序,在(x,y)处单击鼠标,将其移动到(a,b),然后等到鼠标下的颜色为某种颜色,让我们说#fff.当它是那种颜色时,它再次点击然后重复.
我找不到适合python的鼠标相关内容的API.
用于模拟鼠标事件的API取决于您的平台.我不知道任何跨平台的解决方案.
在Windows上,您可以通过ctypes访问Win32 API.在MSDN上看到mouse_event.你可能也对pywinauto感兴趣
要获得鼠标下的颜色,您需要鼠标位置.请参阅MSDN上的GetCursorPos.然后,如果您的应用具有用于获取此位置颜色的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")
Run Code Online (Sandbox Code Playgroud)