首页 > 解决方案 > 如何制作无休止的While循环来检查状态?

问题描述

while pyautogui.locateOnScreen('white4x4.png', region = (200,200,4,4)) != None:
    playsound('click.mp3')
    if pyautogui.locateOnScreen('white4x4.png', region = (200,200,4,4)) == None:
        continue

pyautogui 截图并检查我的图像是否在某个区域,我希望它不断重复

playsound('click.mp3')

当图像可见时,但当它不可见时,我希望它继续检查(重复pyautogui.locateOnScreen)图像是否再次可见。到目前为止,当我隐藏图像时,我的代码结束了,我不知道如何将其保持为“待机”。
另外,我很难理解continue功能,它一次又一次地回去阅读吗?

编辑
我也试过这个

while pyautogui.locateOnScreen('white4x4.png', region = (200,200,4,4)) is not None:
    playsound('click.mp3')
else:
    continue

标签: python

解决方案


在您的代码中,这continue不是必需的,因为continue跳过了循环体的其余部分,然后在检查条件后从顶部重新开始。循环中没有其他内容可以跳过,因此您的代码最好写成:

while pyautogui.locateOnScreen('white4x4.png', region = (200,200,4,4)) is not None:
    playsound('click.mp3')

循环直到条件为假,只有在找不到图像时,条件才会为假。如果您想永远循环播放,请使用while True,并且仅在找到图像时播放声音:

while True:
    if pyautogui.locateOnScreen('white4x4.png', region = (200,200,4,4)) is not None:
        playsound('click.mp3')

推荐阅读