支持屏幕捕获和基于图像的定位,常用于自动化点击按钮。

3.1 捕获屏幕截图

  • 功能:screenshot(image_filename=None, region=None) 捕获屏幕截图,返回 Pillow Image 对象,可保存。
  • 示例:
    img = pyautogui.screenshot('screen.png', region=(0, 0, 300, 400))  # 捕获区域并保存
    

3.2 查找图像位置

  • 功能:locateOnScreen(image, grayscale=False, confidence=0.9, region=None) 在屏幕上查找图像,返回 (left, top, width, height) 或 None。
  • 示例:
    location = pyautogui.locateOnScreen('button.png', confidence=0.8)
    if location:
        print(f"找到位置: {location}")
    

3.3 查找图像中心

  • 功能:locateCenterOnScreen(image, grayscale=False, region=None) 返回图像中心坐标 (x, y) 或 None。
  • 示例:
    center = pyautogui.locateCenterOnScreen('icon.png')
    if center:
        pyautogui.click(center)  # 点击中心
    

3.4 查找所有匹配图像

  • 功能:locateAllOnScreen(image, grayscale=False, region=None) 返回所有匹配图像的生成器,yielding (left, top, width, height)。
  • 示例:
    locations = list(pyautogui.locateAllOnScreen('checkbox.png'))
    print(f"找到 {len(locations)} 个匹配")
    

3.5 获取像素颜色

  • 功能:pixel(x, y) 返回指定坐标的 RGB 颜色 (r, g, b)。
  • 示例:
    color = pyautogui.pixel(100, 100)
    print(f"颜色: {color}")
    

3.6 验证像素颜色

  • 功能:pixelMatchesColor(x, y, expectedRGBColor, tolerance=0) 检查坐标颜色是否匹配,返回 True 或 False。
  • 示例:
    matches = pyautogui.pixelMatchesColor(100, 100, (255, 0, 0), tolerance=10)  # 红色匹配,容差10
    print(f"匹配: {matches}")
    

更多推荐