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

如何在按住鼠标右键时持续执行Python代码,松开即停止?

解决按住右键持续执行代码、松开即停止的问题

你的代码问题出在两点:

  1. on_click函数里的pressed是事件触发时的固定值,按下右键时它是True,但循环过程中这个值不会自动更新,所以while pressed会一直为真。
  2. 这个while循环直接阻塞了鼠标监听线程,导致程序根本无法处理后续的鼠标抬起事件,自然没法停止循环。

下面提供几种可行的解决方案:

方案1:用全局变量+线程(基于pynput)

通过全局变量跟踪右键状态,将执行任务的逻辑放到独立线程中,避免阻塞监听线程:

from pynput import mouse
import threading
import time

# 全局变量记录右键是否被按住
right_button_held = False

def run_task():
    while right_button_held:
        print("Executing code...")
        time.sleep(0.1)  # 添加小延迟,降低CPU占用

def on_mouse_click(x, y, button, pressed):
    global right_button_held
    if button == mouse.Button.right:
        right_button_held = pressed
        # 右键按下时启动任务线程(后台线程随主程序退出)
        if pressed:
            threading.Thread(target=run_task, daemon=True).start()

# 启动鼠标监听
listener = mouse.Listener(on_click=on_mouse_click)
listener.start()
listener.join()

方案2:用类封装状态(更优雅的pynput写法)

用类的实例变量替代全局变量,代码封装性更好,适合复杂场景:

from pynput import mouse
import threading
import time

class RightClickExecutor:
    def __init__(self):
        self.is_right_held = False

    def execute_task(self):
        while self.is_right_held:
            print("Executing code...")
            time.sleep(0.1)

    def on_click(self, x, y, button, pressed):
        if button == mouse.Button.right:
            self.is_right_held = pressed
            if pressed:
                threading.Thread(target=self.execute_task, daemon=True).start()

# 初始化并启动监听
executor = RightClickExecutor()
listener = mouse.Listener(on_click=executor.on_click)
listener.start()
listener.join()

方案3:用pyautogui轮询状态(无需事件监听)

如果不想用事件监听的方式,可以直接轮询鼠标右键的状态,代码更简洁:

import pyautogui
import time

while True:
    # 检查右键是否被按住,是则执行循环
    while pyautogui.mouseIsPressed(button='right'):
        print("Executing code...")
        time.sleep(0.1)
    time.sleep(0.05)  # 主循环添加延迟,减少资源消耗

注意事项

  • 所有方案中添加的time.sleep都是必要的,否则循环会占用大量CPU资源。
  • 使用pyautogui时需要先安装:pip install pyautogui,部分系统可能需要赋予屏幕录制/输入权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 05:33:22