解决方案 | pyautogui实现等待特定图片(对话框)出现(可设置等待超时时间)

发布时间 2023-06-16 20:31:41作者: IssacNew

1、问题

为了等待某个【转换完毕】的图片(对话框)出现,如何设置?

 

 

 

2、解决方案代码如下

下面代码实现的是:设置超时时间为10s,当你在完成前序工作以后,代码开始进入等待,一旦你的特定图片出现了,马上探测到它的位置并且实现点击按钮。

注意:如果等待时间超过了10s,那么就会返回提示:Timed out after 10 seconds.)

 

import pyautogui
import time



## 执行某些工作

# 执行代码区域...

## 下面是等待完成的代码
img_path= r".\\image_for_identify\\free_finished.jpg" #存放特定图片的路径
imageFile =img_path
location = None

start_time = time.time()
timeout = 5  # 设置超时时间

while location is None and time.time() - start_time < timeout:
    location = pyautogui.locateOnScreen(imageFile,grayscale=True, confidence=0.8)
    if location is None:
        time.sleep(0.1)

if location is not None:
    left_pos,top_pos,hei_pos ,width_pos= location
    #"确定"按钮的中心坐标,根据你自己的图像进行计算
    x_c=left_pos+0.8*width_pos
    y_c=top_pos+0.8*hei_pos
    pyautogui.click(x_c,y_c)
else:
    print("Timed out after {} seconds.".format(timeout))