如何循环 PyAutoGUI 的 locateCenterOnScreen 直到找到图像?

How can I loop PyAutoGUI's locateCenterOnScreen until the image is found?

我是 运行 Python Lubuntu 20.04 LTS 上的 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

基于 Why can't pyautogui locate my image although the code seems to be just fine? 看来我的代码不是 运行 一次,也许我应该循环执行以下函数直到检测到图像。

不知道怎么实现,再次基于Why can't pyautogui locate my image although the code seems to be just fine? 以下内容似乎会有所帮助...

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

我定义了一个等于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

如您所见,使用 'waitingloop' 这个过程将一直 运行,然后 每次都失败 来定位图像并且 returns 'None' 它会休眠 0.5 秒并再次尝试 直到它真正找到图像 ,然后当它找到它时,您可以看到它做我想让它做的事情 (在你的情况下它会是 'click') 一旦它这样做,循环就会中断。

希望这段代码能帮到你。