python - 如何循环 PyAutoGUI 的 locateCenterOnScreen 直到找到图像?
问题描述
我在 Lubuntu 20.04 LTS 上运行 Python 3.8.10。
我该如何修改:
a, b = pyautogui.locateCenterOnScreen('/home/image01.png', confidence=0.6, region=(25,500,1700,570))
让它循环直到image01.png
找到?
请看,在我的脚本中,以下内容对我来说大约 90% 的时间有效:
a, b = pyautogui.locateCenterOnScreen('/home/image01.png', confidence=0.6, region=(25,500,1700,570))
但大约 10% 的时间它会失败,导致:
TypeError: 'NoneType' object is not iterable
基于为什么 pyautogui 无法找到我的图像,尽管代码似乎很好?似乎不是运行我的代码一次,也许我应该循环以下函数,直到检测到图像。
我不知道如何实现它,但再次基于Why can't pyautogui locate my image 虽然代码似乎很好? 以下似乎会有所帮助...
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
解决方案
不久前我不得不做类似的事情。
首先,我将“Pyautogui”导入为“pe”,还导入了时间。
所以这就是我所做的。
waitingloop = 1
我定义了一个等于一的等待循环,然后使用我写的
while waitingloop == 1:
if pe.locateCenterOnScreen('signinbox.png') == None:
time.sleep(0.5)
else:
time.sleep(0.5)
pe.typewrite(email)
pe.hotkey('enter')
break
如您所见,使用“等待循环”,此进程将一直运行,然后每次它无法定位图像并返回“无”时,它会休眠 0.5 秒并再次尝试这样做,直到它真正找到image,然后当它找到它时,你可以看到它只是做我想要它做的事情(在你的情况下它会是“点击”),一旦它做到了,循环就会中断。
我希望这段代码可以帮助你。
推荐阅读
- bazel - 如何获取在 Bazel 的 execpath 中创建的文件的文件对象?
- sql-server-2016 - WebSphere 应用程序 (V 8.5.5.0) 到 SQL Server 2016 数据库连接错误
- sql - Concat 然后在 Hive 中分组
- c# - 如何将变量数据从控制器传递到视图(MVC)
- javascript - 如果Server以text/html类型响应,Client会识别不出来吗?
- flutter - 如何获取待处理通知的[scheduledDate](颤动本地通知)
- python - 如何通过特定列的值创建数据框的两个子集?
- java - 我想在 java 程序的帮助下从 azure 监视器中获取活动、密钥库、nsg 流日志等日志,并将它们发送到 tcp/http 端点
- excel - VBA 帮助缩短代码,引入例程?
- javascript - 将地图上的像素 x,y 位置转换为 lat 和 long