首页 > 解决方案 > 尽管代码似乎很好,为什么 pyautogui 无法找到我的图像?

问题描述

所以我的程序应该做的是在默认应用程序窗口 Mozilla Firefox 中找到,然后单击它并将其更改为 Brave Browser。尽管我查看了文档,但发现代码中的所有内容都应如此,但我不断收到此错误:

File "g:\Default-Browser\main.py", line 9, in <module>
    x, y = pyautogui.locateCenterOnScreen('G:\Default-Browser\mozilla.png')
TypeError: cannot unpack non-iterable NoneType object

这是我的代码:

import pyautogui 
from time import sleep

pyautogui.press("win")
sleep(.2)
pyautogui.typewrite("default")
sleep(.1)
pyautogui.press("enter")
x, y = pyautogui.locateCenterOnScreen('G:\Default-Browser\mozilla.png')
pyautogui.moveTo(x, y)
pyautogui.click(x, y)
sleep(.3)
x, y = pyautogui.locateCenterOnScreen(['G:\\Default-Browser\\brave.png'])
pyautogui.click(x, y)
pyautogui.hotkey('alt', 'f4')
quit()

标签: pythonpyautogui

解决方案


未检测到图像,因此 python 无法解压缩变量。您的代码只运行一次图像检测,并且在尝试自动化 GUI 过程时,加载时间可能会因动画、计算机速度等而异,通常只检测一次并不是一个好主意。此外,它不是 100% 可靠的,它可能需要更多的尝试。我总是在自动化过程时使用循环,直到检测到图像。您可以制作如下函数:

def detect_image(path, duration=0):
    while True:
        image_location = pyautogui.locateCenterOnScreen(path)
        if image_location:
            pyautogui.click(image_location[0], image_location[1], duration=duration)
            break

有了这个,你就不会得到那个错误,而且,如果它需要很长时间并且由于某种原因找不到图像,那么你可能应该重新截取屏幕截图。

另一方面,如果您认为图像每次都会发生细微的变化,您可以使用方法confidence中的参数pyautogui.locateCenterOnScreen。置信度越低,就越有可能检测到更多不同的图像。但是,如果您将置信度设置得太低,它可能会检测到误报(不是您真正要查找的图像)。所以你应该意识到降低信心会产生一些问题。代码如下:

pyautogui.locateCenterOnScreen('image.png', confidence=0.5).

请记住,要使用此功能,您必须使用以下 pip 命令安装 opencv pip install opencv-python

最后,如果您想从图片中删除颜色,并检测始终保持不变但颜色发生变化的图像,则可以将grayscale参数传递给 pyautogui 检测方法,这会将图像转换为黑白,然后进行检测。像这样:

pyautogui.locateCenterOnScreen('image.png', grayscale=True)


推荐阅读