首页 > 解决方案 > 如何循环 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

标签: pythonpyautogui

解决方案


不久前我不得不做类似的事情。

首先,我将“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,然后当它找到它时,你可以看到它只是做我想要它做的事情(在你的情况下它会是“点击”),一旦它做到了,循环就会中断。

我希望这段代码可以帮助你。


推荐阅读