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

Python实现后台监听指定区域鼠标点击(非循环轮询)

问题描述

希望程序在后台运行,当点击显示器指定区域时执行一段代码。不想采用循环轮询的方式检测鼠标点击(担心更新间隔中丢失输入),希望程序处于暂停状态,仅在触发鼠标点击事件时运行对应逻辑。

尝试使用mouse库的mouse.on_click()函数,但测试时程序会直接执行代码,不等点击操作就结束,代码如下:

import mouse

def check_for_game(x1, y1, x2, y2):
    mouse.on_click(check_hitbox(x1, y1, x2, y2))


def check_hitbox(x1, y1, x2, y2):
    if x1 <= mouse.get_position()[0] <= x2 and y1 >= mouse.get_position()[1] >= y2:
        print("click in box detected")

check_for_game(0, 1000, 1000, 0)

完全不熟悉事件驱动编程,看到有人使用mouse.hook()函数也无法理解,网上资料未提供有效帮助。

已找到的解决方案

使用pynput的鼠标Listener可以实现需求,以下是可用代码:

from pynput import mouse

def on_click(x, y, button, pressed):
    if pressed and str(button) == "Button.left":
        print(f"left button at {x}, {y}")
    

with mouse.Listener(on_click = on_click) as listener:
    listener.join()

这段代码仅在点击鼠标左键时,将鼠标坐标打印到控制台。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 00:44:58