python - 尽管代码似乎很好,为什么 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()
解决方案
未检测到图像,因此 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)
推荐阅读
- python - Multiple references to the same variable in Python
- wireguard - 无法从一个特定网络连接到wireguard
- python - 对 Pytorch `torch.split` 文档的困惑
- google-chrome - 复制为 curl 在 chrome 中不再起作用
- javascript - 在jquery中通过id、class和attr组合查找元素
- sql - ORACLE 按字母顺序排序大 A,小 a,数字
- javascript - Android Studio 网络视图错误:“未捕获的语法错误:意外的令牌)”
- lua - 我如何制作 2x 现金游戏通行证脚本 Roblox
- android - 如何从 onCreateWindow() 获取传递给 window.open() 的参数
- java - 如何将 tesseract-ocr 与为 Azure Functions 构建的无服务器 Java 应用程序捆绑在一起?