PyAutoGUI无法定位PNG图片求助:多种路径设置均无效
解决PyAutoGUI无法定位PNG图片的问题
核心问题分析
你代码里犯了一个关键错误:在is_image_on_screen函数中,你已经生成了图片的绝对路径image_path_absolute,但实际调用pyautogui.locateOnScreen时,还是用的传入的相对路径image_path,等于之前的路径处理完全没生效!这就是换路径、生成绝对路径都没用的原因。
修正后的完整代码
import time import pyautogui import os # 检查屏幕上是否存在指定图片 def is_image_on_screen(image_path, region=None, confidence=0.7): try: # 获取脚本所在目录的绝对路径 script_directory = os.path.dirname(os.path.abspath(__file__)) # 拼接图片的绝对路径 image_path_absolute = os.path.join(script_directory, image_path) # 使用生成的绝对路径进行查找 location = pyautogui.locateOnScreen(image_path_absolute, region=region, confidence=confidence) return location is not None except Exception as e: print(f"查找图片时出错: {e}") return False # 延迟5秒,方便切换到目标窗口 time.sleep(5) # 检查是否有广告 script_dir = os.path.dirname(os.path.abspath(__file__)) if is_image_on_screen("mark.png"): # 点击广告位置 advert_location = pyautogui.locateOnScreen(os.path.join(script_dir, "mark.png")) advert_center = pyautogui.center(advert_location) pyautogui.click(advert_center) # 滚动屏幕寻找广告 pyautogui.scroll(100) # 关闭按钮图片列表 close_button_images = ['close.png', 'close2.png', 'close3.png'] # 遍历寻找关闭按钮并点击 for close_button_image in close_button_images: img_abs_path = os.path.join(script_dir, close_button_image) if is_image_on_screen(close_button_image): close_button_location = pyautogui.locateOnScreen(img_abs_path) close_button_center = pyautogui.center(close_button_location) pyautogui.click(close_button_center) pyautogui.hotkey('alt', 's')
额外排查步骤
如果修正后仍报错,按以下步骤排查:
- 确认
mark.png、close.png等文件确实在脚本所在文件夹内,文件名拼写完全一致(注意大小写:Windows不区分,但Linux/macOS严格区分) - 检查图片文件权限,确保当前运行脚本的用户有读取权限
- 验证图片完整性:用系统图片查看器打开,确认不是损坏的PNG文件
- 若使用
confidence参数,确保已安装opencv-python(PyAutoGUI图像识别依赖该库,执行pip install opencv-python安装)
报错信息翻译
ERROR: [ WARN:0@5.244] global loadsave.cpp:248 cv::findDecoder imread_('close3.png'): 无法打开/读取文件:请检查文件路径/完整性
无法读取close3.png,原因是文件缺失、权限不正确,或者是不支持的无效格式
内容的提问来源于stack exchange,提问作者Shinobu
相关产品推荐
相关产品推荐

