Skip to main content
 首页 » 编程设计

python之为什么我的 if 在循环中发出哔哔声

2025年05月04日15jirigala

我正在使用 pyautogui单击在我的 GUI 上定期弹出的按钮,如下面的脚本所示。但是,当按钮不在屏幕上时,脚本会在循环过程中发出两声恼人的哔哔声。

如果我将 pyautogui.locateOnScreen(...) 替换为 None,如果无法在屏幕上定位图像,这似乎是返回值,声音似乎消失了。

该脚本使用 python 2.7 在 Jupyter Notebook (v4) 中运行,我在 Debian 8.1 和 Gnome 上运行。

import pyautogui 
import time 
 
starttime = time.time()   
 
while time.time()-starttime<10: 
    img_path_inactive = "/home/user/folder/inactive_target.png" 
    img_path_active = "/home/user/folder/active_target.png" 
    img_list = [img_path_inactive, img_path_active] 
    get_target = map(pyautogui.locateOnScreen, img_list)  # <--- This line beeps! See edit 2 
 
    if any(get_target): 
        pyautogui.click(filter(None, get_target)[0][0], filter(None, get_target)[0][1]) 
 
    # The if check above was previously (hence the title): 
    # if pyautogui.locateOnScreen(img_path_active) or pyautogui.locateOnScreen(img_path_inactive): 
    #     click_target = pyautogui.locateOnScreen(img_path_active) or pyautogui.locateOnScreen(img_path_inactive) 
    #     pyautogui.click(click_target[0], click_target[1]) 
 
    time.sleep(2) 
 
print("Finished loop.") 

编辑

我将脚本放在一个 .py 文件中,然后从命令行运行它以检查它是否是 jupyter 的东西。但它仍然发出哔哔声。

之后,我针对三张图片运行了 pyautogui.locateOnScreen,结果不出所料地发出了三声哔哔声……所以这肯定是 pyautogui 问题/“功能”……

编辑2

pyautogui.locateOnScreen 是从 here 导入的,请参阅第 238 行。它实际上确实引发了异常:

    except ImageNotFoundException: 
        if time.time() - start > minSearchTime: 
            raise 

请您参考如下方法:

我也在 GNU/Linux 上,并且在 pyautogui.locateOnScreen() 函数运行时遇到蜂鸣声(无论它是否找到图像)。

我发现 scrot 是罪魁祸首。解决方案:

  1. $ sudo mv/usr/bin/scrot/usr/bin/scrot-noisy

  2. 使用这些内容创建/usr/bin/scrot:

#!/bin/bash

scrot-noisy --silent "$@"

  1. $ sudo chmod a+x/usr/bin/scrot