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

使用pynput实现右键释放后复位光标位置不生效,如何解决?

问题原因
  • 未区分按键状态:pynput的on_click回调的pressed参数,True代表按键按下,False代表按键释放。你的代码没有做状态区分,只要触发右键事件就将鼠标位置设置为当前触发坐标,相当于没有实际移动效果。
  • 未持久化存储按下坐标:代码中定义的placeX、placeY是on_click函数的局部变量,右键按下时存储的坐标在函数执行结束后就会销毁,右键释放时无法读取到按下时的原始坐标值。
修正后可实现需求的代码
from pynput.mouse import Button, Controller, Listener

mouse = Controller()
# 全局变量存储右键按下时的原始坐标
press_origin_x = 0
press_origin_y = 0

def on_click(x, y, button, pressed):
    global press_origin_x, press_origin_y
    if button == Button.right:
        if pressed:
            # 右键按下时记录当前坐标
            press_origin_x = x
            press_origin_y = y
        else:
            # 右键释放时将鼠标移动到按下时的坐标
            mouse.position = (press_origin_x, press_origin_y)
            # 若不需要弹出系统右键菜单,可去掉下方注释,阻止右键默认行为
            # return False


with Listener(
        on_click=on_click
) as listener:
    listener.join()
补充说明

如果测试时发现系统弹出的右键菜单干扰了光标移动效果,可以去掉代码中return False的注释,即可屏蔽右键点击的系统默认行为,保证光标移动逻辑正常生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 18:36:04