首页 > 解决方案 > 为什么我的 pyautogui 代码不能正常工作

问题描述

我创建了一个简单的脚本来在桌面上查找图像,然后输入“我找到了”,如果我隐藏图像,则脚本类型“我无法找到它”。

添加另一个动作时的问题,即我希望鼠标移动到图像的位置。该脚本运行良好,但是当我隐藏图像时,鼠标仍然移动到该位置,并且仍然键入我找到了它。但通常代码应该告诉我我找不到它。脚本仍在处理 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")

标签: pythonpyautogui

解决方案


你存储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")

推荐阅读