以下是一个基于Python的按键精灵找图点击功能的封装代码示例,使用`pyautogui`和`opencv`库实现: ```python import pyautogui import cv2 import time from typing import Tuple, Optional class ImageClicker: """ 屏幕找图并点击的封装类 功能:在屏幕上查找目标图片,找到后执行点击操作 """ def __init__(self, confidence: float = 0.8, wait_time: float = 1.0): """ 初始化参数 :param confidence: 识别置信度(0-1),默认0.8 :param wait_time: 每次操作后的等待时间(秒),默认1秒 """ self.confidence = confidence self.wait_time = wait_time def find_image(self, target_image: str) -> Optional[Tuple[int, int]]: """ 在屏幕上查找目标图片 :param target_image: 目标图片路径 :return: 图片中心坐标(x,y)或None """ try: # 使用pyautogui定位图片 location = pyautogui.locateOnScreen(target_image, confidence=self.confidence) if location: center_x = location.left + location.width // 2 center_y = location.top + location.height // 2 return (center_x, center_y) except Exception as e: print(f"找图失败: {e}") return None def click_image(self, target_image: str, click_count: int = 1) -> bool: """ 查找并点击图片 :param target_image: 目标图片路径 :param click_count: 点击次数,默认1次 :return: 是否点击成功 """ position = self.find_image(target_image) if position: pyautogui.moveTo(position[0], position[1]) time.sleep(self.wait_time/2) pyautogui.click(clicks=click_count) time.sleep(self.wait_time) return True return False def wait_and_click(self, target_image: str, timeout: float = 10.0, interval: float = 1.0) -> bool: """ 等待图片出现并点击(轮询方式) :param target_image: 目标图片路径 :param timeout: 超时时间(秒) :param interval: 检查间隔(秒) :return: 是否点击成功 """ start_time = time.time() while time.time() - start_time < timeout: if self.click_image(target_image): return True time.sleep(interval) return False # 使用示例 if __name__ == "__main__": clicker = ImageClicker(confidence=0.9) # 单次查找点击 clicker.click_image("button.png") # 等待点击(最多等10秒,每秒检查一次) clicker.wait_and_click("popup.png", timeout=10) ``` 代码说明: 1. 使用`pyautogui`实现屏幕操作和图像识别 2. 封装了三种常用操作:查找图片、直接点击、等待点击 3. 添加了置信度参数应对图像识别误差 4. 每次操作后自动等待防止操作过快 三条额外需要注意的逻辑点: 1. 屏幕分辨率变化会导致识别失败,建议使用相对坐标或分辨率适配方案 2. 目标图片需要保持原样(不能有遮挡或变形) 3. 高频率找图操作会消耗大量CPU资源,建议适当添加延迟 [2025-08-05 05:08:51 | AI写代码神器 | 787点数解答]