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

如何用pydirectinput替代pyautogui实现locateCenterOnScreen功能?

解决pydirectinput无locateCenterOnScreen功能的问题

问题背景

当前使用以下Python代码,通过pyautogui的locateCenterOnScreen定位图像并执行点击操作:

import time
import keyboard
import pyautogui
import win32api
import win32con

time.sleep(3)


def click():
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0)
    time.sleep(0.1)


while not keyboard.is_pressed('q'):
    start = pyautogui.locateCenterOnScreen('img.png', region=(0, 0, 1920, 1080), grayscale=True, confidence=0.50)
    if start is not None:
        pyautogui.moveTo(start)
        click()

尝试用pydirectinput替换pyautogui时,发现pydirectinput没有locateCenterOnScreen功能,无法完成图像定位操作。

解决方案

pydirectinput专注于输入模拟(比如提升游戏场景下的键鼠操作兼容性),本身没有集成图像识别模块。无需完全替换pyautogui,拆分职责即可:

  • 保留pyautogui负责图像识别与坐标定位(locateCenterOnScreen)
  • 使用pydirectinput替换鼠标移动、点击等输入操作

修改后的代码如下:

import time
import keyboard
import pyautogui
import pydirectinput

time.sleep(3)

while not keyboard.is_pressed('q'):
    # 用pyautogui完成图像定位
    start = pyautogui.locateCenterOnScreen('img.png', region=(0, 0, 1920, 1080), grayscale=True, confidence=0.50)
    if start is not None:
        # 用pydirectinput执行鼠标操作
        pydirectinput.moveTo(start.x, start.y)
        pydirectinput.click()
        time.sleep(0.1)

补充说明

  • pydirectinput的moveTo和click方法可以直接替代原代码中的pyautogui.moveTo和自定义click函数,无需额外调用win32api
  • 这种混合使用的方式既保留了pyautogui的图像识别能力,又利用了pydirectinput在输入模拟上的优势,比如规避部分游戏对pyautogui的检测

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 16:23:17