如何运行无限while循环直到在Python中找到值?
到目前为止,我对Python还比较陌生,学习起来很有趣 我试图使用Python及其库Pyautogui找到按钮的位置 这是我的密码如何运行无限while循环直到在Python中找到值?,python,loops,infinite,pyautogui,Python,Loops,Infinite,Pyautogui,到目前为止,我对Python还比较陌生,学习起来很有趣 我试图使用Python及其库Pyautogui找到按钮的位置 这是我的密码 import webbrowser, pyautogui, time, datetime class workDoneClicker: def buttonTrack(self): global x, y x = () y = () while x == (): co
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函数获取值需要几秒钟,因为它必须加载网页。
但当我运行代码点击器时,它似乎在找到值之前不会执行无限循环,而是运行下一个代码,因为我得到了“非类型”对象不可下标 我可以问一下如何像我期望的那样跑步吗?还有解释 如果在屏幕上找不到图像,locateOnScreen()将返回None 因此,如果未找到
image.png
,坐标将变为None
,这会在下一行抛出错误,因为您无法对None
对象执行[0]
添加一个“无”条件,它应该可以工作
coordinate = pyautogui.locateOnScreen('image.png')
if coordinate is not None:
x, y = (coordinate[0], coordinate[1])
return x, y
当找不到按钮并且您尝试执行坐标[0]时,pyautogui.locateOnScreen()函数将返回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")
我以前从未使用过此API,但通过查看您问题中的文档和详细信息,我将尝试回答您的问题。 要运行无限循环,只需使用
,而True:
关于你的问题:
x = ()
y = ()
while True:
coordinate = pyautogui.locateOnScreen('image.png')
if coordinate:
x, y = (coordinate[0], coordinate[1])
return x, y
是否要为
x
查找某个值或任何值?在这种情况下,我是否可以理解(否则:continue)下的句子(返回x,y是)被省略了?@KimHyungJune不需要显式编写continue语句,因为它是一个无限循环,除非给出中断条件,否则将迭代。“继续”使您返回到循环的开头,跳过循环中的其余操作。这里没有这样的。