寻找屏幕上的caputura图像,即使它不在那个时刻

2024-09-28 22:23:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: 代码importtrueautotimepngusersfile
1条回答
网友
1楼 · 发布于 2024-09-28 22:23:44

当找不到映像时,它将引发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)

相关问题 更多 >