【问题标题】:how to run infinite while loop until it finds the value in Python?如何运行无限while循环,直到它在Python中找到值?
【发布时间】:2018-08-21 06:49:56
【问题描述】:

到目前为止,我对 Python 还是比较陌生,学习很有趣。

我想做的是使用 Python 及其库 Pyautogui 找到按钮的位置。

这是我的代码。

import webbrowser, pyautogui, time, datetime

class workDoneClicker:

    def buttonTrack(self):
        global x, y
        x = ()
        y = ()
        while x == ():
            coordinate = pyautogui.locateOnScreen('image.png')
            x, y = (coordinate[0], coordinate[1])
            return x, y

    def clicker(self):         

        if pyautogui.alert(text="hi", title="hi") == 'OK':
            webbrowser.open('http://example.com')
            time.sleep(3)
            self.buttonTrack()
            self.clickButton()
            print("executed")

        else:
           print("not executed")

我要做的是执行buttonTrack函数,直到找到值,然后返回x,y。
并在 clicker 函数中运行下一个代码。
使用 buttonTrack 函数获取值需要几秒钟,因为它必须加载网页。
但是当我运行代码点击器时,它似乎在找到值之前不会执行无限循环,而是运行下一个代码,因为我得到 'NoneType' object is not subscriptable

请问如何按预期运行?和解释?

【问题讨论】:

  • 你想为你的x找到某个值或任何值吗?

标签: python loops infinite pyautogui


【解决方案1】:

如果在屏幕上找不到图片,locateOnScreen() 返回 None。

http://pyautogui.readthedocs.io/en/latest/screenshot.html

因此,如果找不到image.png,坐标变为None,这会在下一行引发错误,因为您不能对None 对象执行[0]

添加一个无条件,它应该可以工作。

coordinate = pyautogui.locateOnScreen('image.png')
if coordinate is not None:
    x, y = (coordinate[0], coordinate[1])
    return x, y

【讨论】:

    【解决方案2】:

    pyautogui.locateOnScreen() 函数在未找到按钮并且您尝试执行坐标 [0] 时返回 None,这会引发错误,因为 None 不可下标。您可以添加一个检查,如果坐标的值不是 None 则仅填充 x 和 y 值。

    class workDoneClicker:
      def buttonTrack(self):
        global x, y
        x = ()
        y = ()
        while x == ():
            coordinate = pyautogui.locateOnScreen('image.png')
            if(coordinate is not None):
                x, y = (coordinate[0], coordinate[1])
                return x, y
    def clicker(self):
        if pyautogui.alert(text="hi", title="hi") == 'OK':
            webbrowser.open('http://example.com')
            time.sleep(3)
            self.buttonTrack()
            self.clickButton()
            print("executed")
        else:
            print("not executed")
    

    【讨论】:

    • 在这种情况下,我可以理解为省略了句子 (return x,y is) 下的 (else:
      continue) 吗?
    • @KimHyungJune 不需要显式编写 continue 语句,因为它是一个无限循环,除非给出中断条件,否则它将进行迭代。 continue 让您回到循环的开头,跳过循环中的其余操作。这里没有这样的。
    【解决方案3】:

    我以前从未使用过此 API,但通过阅读您问题中的文档和详细信息,我将尝试回答。 要运行无限循环,您可以使用 while True: 根据您的问题:

    x = ()
    y = ()
    while True:
        coordinate = pyautogui.locateOnScreen('image.png')
            if coordinate:
                x, y = (coordinate[0], coordinate[1])
                return x, y
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-29
      • 2020-05-17
      • 1970-01-01
      • 2020-09-29
      • 2014-01-12
      • 2011-06-10
      • 2017-10-12
      • 2020-11-30
      相关资源
      最近更新 更多