为什么我的 pyautogui 代码不能正常工作

why does my pyautogui code not works good

我创建了一个简单的脚本来在桌面上查找图像,然后键入 'I found it ',如果我隐藏图像,脚本类型 'I am unable to found it'.

当我添加另一个动作时出现问题,我希望鼠标移动到图像的位置。该脚本运行良好,但是当我隐藏图像时,鼠标仍然移动到该位置,并且仍然键入我找到它的位置。但通常代码应该告诉我我无法找到它。 脚本仍在处理 if 而不是移动到 else。

我的代码是:

import pyautogui
import time

location = pyautogui.locateOnScreen('image.png', confidence = 0.6)

while 1:
    if location:
        print("I found it ")
        time.sleep(2)
        print(pyautogui.moveTo(location))

    else:
        print("I am unable to found it")

您将 pyautogui.locateOnScreen('image.png', confidence = 0.6) 存储在变量 location 中。然后检查条件 (if/else)。但是你永远不会重新检查 pyautogui.locateOnScreen('image.png', confidence = 0.6)。我仍然不确定你想在这里实现什么,但至少检查需要进入 while:

while 1:
    location = pyautogui.locateOnScreen('image.png', confidence = 0.6)
    if location:
        print("I found it ")
        time.sleep(2)
        print(pyautogui.moveTo(location))
    else:
        print("I am unable to find it")