首页 > 解决方案 > 通过屏幕的caputura寻找图像,即使它不在那个时刻

问题描述

如果我想查找图像,我可以使用什么代码,即使它不是在那个时刻,而是在找到它的时候?我的代码是:

import pyautogui as auto
import time
import pyautogui


def Saludar (seconds,schedule) :

    while (1>0) and (schedule == True) :
        time.sleep(seconds)

        x, y = auto.locateCenterOnScreen('linea.png', grayscale=True)
        auto.moveTo(x,y)
        pyautogui.click()
        print("YA")



if __name__== "__main__":
    Saludar(2,True)

错误:

Traceback (most recent call last):
  File "C:/Users/mario/Desktop/buscar aun si no está.py", line 19, in <module>
    Saludar(2,True)
  File "C:/Users/mario/Desktop/buscar aun si no está.py", line 11, in Saludar
    x, y = auto.locateCenterOnScreen('linea.png', grayscale=True)
TypeError: 'NoneType' object is not iterable

标签: pythonpyautogui

解决方案


当找不到图像时,它会引发TypeError异常。您可以简单地使用try/except来处理它:

import pyautogui as auto
import time
import pyautogui


def Saludar(seconds, schedule):
    while (1 > 0) and (schedule == True):
        time.sleep(seconds)
        try:
            x, y = auto.locateCenterOnScreen(
                'Desktop/linea.png', grayscale=True)
            print('Found it!')
            auto.moveTo(x, y)
            pyautogui.click()
        except TypeError:
            """
            Image is not found
            """
            print("Image is Not found on the screen!")


if __name__ == "__main__":
    Saludar(2, True)

推荐阅读