pyautogui 像素颜色扫描器,手动有效但自动化无效
我正在尝试创建一个简单的像素扫描器,方法是把鼠标从一个位置向下移动,直到碰到特定的颜色。我可以手动做到这一点,而且效果很好,但一旦我尝试自动化这个过程,它就失败了。
Python版本
Python 3.11.5
import pyautogui
while True:
try:
# Start positon of the mouse <---- Automation
pyautogui.moveTo(899,50)
# Gets the positon
position = pyautogui.position()
# Gets the color of pixel
color_matching = pyautogui.pixel(position.x,position.y)
# Prints the pixel in format (255,255,255)
print(color_matching)
# - Green -
#If the color matches prints "Found Green!"
if color_matching == (86,183,39):
print("Found Green!")
break
# - Red -
#If the color matches prints "Found Red!"
if color_matching == (244,59,13):
print("Found Red!")
break
# End positon of the mouse <---- Automation
pyautogui.moveTo(899,1000,5)
except:
break
在没有自动化的情况下,我可以通过把鼠标移动到我选择的颜色上来让它工作。
但是在自动化的情况下,它只会在移动到这段代码时捕捉到第一个像素:
pyautogui.moveTo(899,50)
如果没有自动化,我只要在颜色匹配的地方加一个打印,它就会不断更新,但有了自动化后……正如之前提到的,它只会打印一次。
那么,我该怎么才能让它正常工作呢?我也希望它能运行得快一点,但首先我只想让它能正常工作。
1 个回答
1
我觉得你可以通过使用线程来解决这个问题。下面是代码:
import pyautogui
import threading
# Variable to control the scanning state
scanning = False
def startScan():
global scanning
scanning = True
pyautogui.moveTo(899, 1000, 5) # Move the mouse to a specific position
scanning = False
while True:
try:
if not scanning: # If scanning is completed, start again
pyautogui.moveTo(899, 50) # Start position of the mouse (Automation)
# Start a new thread for moving the mouse
threading.Thread(target=startScan, daemon=True).start()
# Get the mouse position
position = pyautogui.position()
# Get the color of the pixel
color_matching = pyautogui.pixel(position.x, position.y)
# Print the pixel color in the format (255, 255, 255)
print(color_matching)
# Green
# If the color matches, print "Found Green!" and exit the loop
if color_matching == (86, 183, 39):
print("Found Green!")
break
# Red
# If the color matches, print "Found Red!" and exit the loop
elif color_matching == (244, 59, 13):
print("Found Red!")
break
except:
break