Python 使用 for 和 while 循环

问题描述 投票:0回答:1

目前我有这个

for word in words:
   print(word)

但现在我想引入一个 while 循环,只要图像(spinner.png)位于屏幕上就只执行该循环。像这样

while True:

    try:    
       location = pyautogui.locateOnScreen('c:/images/spinner.png', region=(140, 240, 300, 100), confidence=0.5) 
       for word in words:
              print(word)
    except pyautogui.ImageNotFoundException:
       pass

或者像这样:

for word in words:

   while True:

    try:    
       location = pyautogui.locateOnScreen('c:/images/spinner.png', region=(140, 240, 300, 100), confidence=0.5) 
       print(word)
    except pyautogui.ImageNotFoundException:
       pass

并且也在寻找Pythonic方式。但在内循环中的中断处阅读了许多 kb 却感到困惑。

我还没有尝试过任何东西,只是想知道最有效的编码方法

while True:

    try:    
       location = pyautogui.locateOnScreen('c:/images/spinner.png', region=(140, 240, 300, 100), confidence=0.5) 
       for word in words:
              print(word)
    except pyautogui.ImageNotFoundException:
       pass
python loops for-loop while-loop
1个回答
0
投票

我认为你的第一种方法效果最好,因为你只需要检查图像是否在屏幕上出现一次,然后打印

possible-words
列表中的所有元素。这样您只需要检查一次,而第二个选项您必须检查
possible-words
列表中的每个元素。另外我认为最好在
break
循环中添加一个
while
来在图像出现在屏幕上时跳出循环,以避免陷入无限循环

while True:
    try:    
       location = pyautogui.locateOnScreen('c:/images/spinner.png', region=(140, 240, 300, 100), confidence=0.5) 
       for word in possible_words:
           print(word)
       break
    except pyautogui.ImageNotFoundException:
       pass
© www.soinside.com 2019 - 2024. All rights reserved.