gpt4 book ai didi

python - 如何运行无限while循环直到找到Python中的值?

转载 作者:太空宇宙 更新时间:2023-11-03 14:00:51 24 4
gpt4 key购买 nike

我对 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。
并在点击器函数中运行下一个代码。
使用buttonTrack函数获取值需要几秒钟,因为它必须加载网页。
但是当我运行代码点击器时,它似乎不会执行无限循环,直到找到该值,而是运行下一个代码,因为我得到“NoneType”对象不可下标

请问如何按照我的预期运行?以及解释?

最佳答案

当找不到按钮并且您尝试执行坐标[0]时,pyautogui.locateOnScreen() 函数将返回 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")

关于python - 如何运行无限while循环直到找到Python中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49248978/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com