【问题标题】:Coditioning in python loopspython循环中的条件
【发布时间】:2021-03-19 15:28:05
【问题描述】:
import time
import pyautogui


location = pyautogui.locateOnScreen('ok.png')

pyautogui.click(location)

如何将以下语句编写为代码?

如果屏幕上没有找到图像,请继续运行location,直到找到图像。

否则代码将立即终止。

我试过了:

While location == None : #Or location == False
    pyautogui.click(location)

【问题讨论】:

    标签: python loops screen screenshot pyautogui


    【解决方案1】:

    尝试像这样使用while

    while location is not None:
        pyautogui.click(location)
    

    【讨论】:

      【解决方案2】:

      根据Pyautogui documentation

      如果在屏幕上找不到图像,locateOnScreen() 会引发 ImageNotFoundException

      这意味着您必须处理错误消息,以便在图像不存在的情况下保持程序运行。 尝试使用异常处理:

      import pyautogui
      
      while True:
          # Try to do this
          try:
              location = pyautogui.locateOnScreen('ok.png')
              # Location found with no errors: break the while loop and proceed
              break
          # If an error has occurred (image not found), keep waiting
          except:
              pass
      
      pyautogui.click(location)
      

      注意:这会生成一个无限循环,直到在屏幕上找到图像。要中断此循环并停止脚本执行,请在 Shell 上使用 CTRL+C。

      或者,您可以设置等待图像的最长时间:

      import time
      import pyautogui
      
      max_wait = 30 # Seconds
      end = time.time() + max_wait
      
      while time.time() <= end:
          # Try to do this
          try:
              location = pyautogui.locateOnScreen('ok.png')
              # Location found with no errors: break the while loop and proceed
              break
          # If an error has occurred (image not found), keep waiting
          except:
              pass    
          
      pyautogui.click(location)
      

      【讨论】:

        猜你喜欢
        • 2019-06-04
        • 1970-01-01
        • 2011-05-18
        • 1970-01-01
        • 2019-11-07
        • 2021-11-25
        • 2022-01-01
        • 2013-03-09
        • 1970-01-01
        相关资源
        最近更新 更多