You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用pyautogui的locateCenterOnScreen同时查找两张图片

解决方案

核心问题出在你原有imageFind函数内置了死循环,调用该函数时会一直阻塞直到匹配到传入的图片,所以才会卡在Edge的检测逻辑不走Firefox的检测。按照如下两步调整即可实现需求:

1. 重构imageFind函数,移除内部循环,改为单次检测

把imageFind的内置循环去掉,单次检测不到对应图片就返回(0,0),让外层循环来控制检测逻辑:

def imageFind(image,g,double):
    a = 0
    b = 0
    try:
        a,b = p.locateCenterOnScreen(image,grayscale=g)
    except TypeError:
        pass
    # 只有找到坐标的时候才执行点击,没找到就不操作
    if a !=0 and b !=0:
        if double == True:
            time.sleep(1)
            p.doubleClick(a,b)
        else:
            p.click(a,b)
    return a,b

2. 调整外层轮询逻辑,交替检测两张图片

外层循环每次依次检测Edge和Firefox,任意一个匹配成功就触发对应逻辑,匹配失败则继续下一轮检测:

# 抽离公共的打开记事本写结果逻辑,减少重复代码
def open_notepad_and_write(content):
    p.hotkey("win")
    time.sleep(1)
    p.write("notepad")
    time.sleep(1)
    p.press("enter")
    time.sleep(1)
    p.write(content)

# 主检测逻辑
while True:
    edge_pos = imageFind("Edge.png",False,False)
    if all(edge_pos):
        open_notepad_and_write("Found Edge")
        break
    firefox_pos = imageFind("Firefox.png",False,False)
    if all(firefox_pos):
        open_notepad_and_write("Found Firefox")
        break
    # 加短休眠避免占满CPU资源,可根据需求调整时长
    time.sleep(0.1)

优化说明

  • 单次检测逻辑每次循环都会交替检查两张图片,哪张先出现就会先匹配到,符合需求
  • 增加短休眠降低CPU占用,不会影响检测的实时性
  • 抽离重复逻辑后代码更易维护,后续如果要加更多检测图片,只需要在循环里加对应检测分支即可

内容的提问来源于stack exchange,提问作者theshape

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 07:39:00