首页 > 解决方案 > Python while / if循环忽略条件

问题描述

我正在编写一个基本while/if循环来在屏幕上没有时向下滚动页面nextbutton.png,并在按钮在屏幕上时停止滚动。

True如果按钮不在屏幕上,它应该打印,如果是,则打印按钮的位置。问题是,当我运行此代码时,我得到以下输出:

True
True
True
True
True
True
True
True
True
True
True
True
True
True
False

这段代码的编写方式,它不应该输出False,或者True位置。我可以向我正在尝试的网站提供有关如何复制输出的说明,但我怀疑我在构建循环时犯了一个简单的逻辑错误。

import pyautogui
while True:
    if pyautogui.locateOnScreen('nextbutton.png', confidence=0.9) is None:
        print(pyautogui.locateOnScreen('nextbutton.png', confidence=0.9) is None)
        time.sleep(random.randint(0,3000)/1000) 
        pyautogui.press('pagedown')
    else:
        x4, y4 = pyautogui.locateCenterOnScreen('nextbutton.png', confidence=0.9)
        print(x4,y4)
        break

标签: pythonwhile-looppyautogui

解决方案


您调用该函数locateOnScreen()2 次,它可能每次返回不同的输出。

我建议使用一个变量来保存的输出locateOnScreen()以避免这种竞争条件。也许这对你有用:

import pyautogui

while True:
    v = pyautogui.locateOnScreen('nextbutton.png', confidence=0.9)
    if v is None:
        print(v is None)
    ...

推荐阅读