You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyAutoGUI locateOnScreen失效求助:数学游戏自动答题程序故障

问题描述

我是Python初学者,正在开发一款数学游戏自动答题程序。此前使用if pyautogui.locateOnScreen语句可正常运行(为随机问题匹配随机答案),但现在程序完全无法答题。以下是代码片段:

from pyautogui import * 
import pyautogui 
import time 
import keyboard 
import random
import win32api, win32con

if pyautogui.locateOnScreen('6x8.png', region=(350,240,500,95), grayscale=True, confidence=0.9) != None:
         pyautogui.write('48')
         pyautogui.press('enter')
         print("48")
         while True:
          break
          
sleep(0.01) 
if pyautogui.locateOnScreen('8x6.png', region=(350,240,500,95), grayscale=True, confidence=0.9) != None:
  pyautogui.write('48')
  pyautogui.press('enter')
  print("48")
  while True:
   break
                 

sleep(0.01)
if pyautogui.locateOnScreen('88d11.png', region=(350,240,500,95), grayscale=True, confidence=0.9) != None:
    pyautogui.write('8')
    pyautogui.press('enter')
    print("8")
    while True:
     break

类似的代码约有400行,恳请帮忙排查故障原因。

故障排查与解决方案

1. 图像匹配精度问题

  • confidence=0.9阈值过高,游戏界面可能存在细微变化(比如窗口缩放、颜色偏差、字体渲染差异)导致匹配失败,先降到0.7左右测试,确认是否能匹配到目标图像。
  • 检查grayscale=True是否适用,若游戏问题图像有颜色区分,关闭灰度模式可能提升匹配成功率。

2. 图像文件本身问题

  • 重新截取当前游戏中的问题图像替换旧的6x8.png等文件,确保图像与当前界面完全一致(包括尺寸、像素、周围背景)。
  • 用os.path.exists('6x8.png')验证图像文件路径是否正确,确保程序运行时能读取到这些图片。

3. 区域定位错误

  • 确认region=(350,240,500,95)参数格式正确(left, top, width, height),若游戏窗口位置或大小变化,会导致区域偏移。可通过pyautogui.displayMousePosition()实时查看鼠标位置,重新校准区域坐标。

4. 程序逻辑缺陷

  • 每个if块内的while True: break是无效代码,直接删除即可。
  • 400行连续if判断仅执行一次就结束,无法持续检测新问题。需将所有判断放入循环,比如用while not keyboard.is_pressed('q'):持续运行,直到按下q键退出,示例:
import pyautogui
import time
import keyboard

while not keyboard.is_pressed('q'):  # 持续运行直到按q退出
    if pyautogui.locateOnScreen('6x8.png', region=(350,240,500,95), grayscale=True, confidence=0.7):
        pyautogui.write('48')
        pyautogui.press('enter')
        print("48")
        time.sleep(0.5)  # 处理完一题后短暂等待,避免重复触发
    if pyautogui.locateOnScreen('8x6.png', region=(350,240,500,95), grayscale=True, confidence=0.7):
        pyautogui.write('48')
        pyautogui.press('enter')
        print("48")
        time.sleep(0.5)
    # 其他问题判断...
    time.sleep(0.01)
  • 原代码重复导入pyautogui,保留import pyautogui即可,避免命名冲突。

5. 依赖库版本问题

  • pyautogui的图像匹配依赖opencv-python,若版本更新导致兼容性问题,可回退到之前能用的版本,比如执行:pip install pyautogui==0.9.53 opencv-python==4.5.5.62。

6. 系统权限与窗口状态

  • 确保程序以管理员身份运行,避免权限不足无法捕获屏幕图像。
  • 游戏窗口需处于前台,pyautogui无法捕获最小化或被遮挡的窗口内容。

内容的提问来源于stack exchange,提问作者Vantrix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 04:20:29