我正在尝试创建一个简单的像素扫描仪,将鼠标从一个位置向下移动,直到它达到特定的颜色。我可以简单地手动执行此操作,并且效果完美,但是一旦我对其实施自动化,它就无法执行此操作。
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)
如果没有它,如果我只是将打印添加到 color_matching 中,它会不断更新,但是有了它......它会像之前提到的那样只打印一次。
那么,我怎样才能让它发挥作用呢?我也希望它运行得快,但首先我只想它能工作。
我认为你可以通过线程来解决这个问题。这是代码:
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