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

如何实现按住鼠标左键启动自动点击、松开停止的Python脚本?

实现按住鼠标左键自动点击、松开停止的修改方案

修改后的完整代码

import time
import threading
from pynput.mouse import Button, Controller, Listener
from pynput.keyboard import Listener as KeyboardListener, KeyCode

# 自动点击配置
delay = 0.277
click_button = Button.left
stop_key = KeyCode(char='-')

class ClickMouse(threading.Thread):
    def __init__(self, delay, button):
        super(ClickMouse, self).__init__()
        self.delay = delay
        self.button = button
        self.running = False
        self.program_running = True

    def start_clicking(self):
        self.running = True

    def stop_clicking(self):
        self.running = False

    def exit(self):
        self.stop_clicking()
        self.program_running = False

    def run(self):
        while self.program_running:
            while self.running:
                mouse.click(self.button)
                time.sleep(self.delay)
            time.sleep(0.1)

# 初始化鼠标控制器和点击线程
mouse = Controller()
click_thread = ClickMouse(delay, click_button)
click_thread.start()

# 鼠标事件处理:按住左键启动,松开停止
def on_click(x, y, button, pressed):
    if button == click_button:
        if pressed:
            click_thread.start_clicking()
            print("自动点击启动")
        else:
            click_thread.stop_clicking()
            print("自动点击停止")

# 键盘事件处理:按'-'键退出程序
def on_key_press(key):
    if key == stop_key:
        click_thread.exit()
        # 停止两个监听器
        mouse_listener.stop()
        keyboard_listener.stop()
        print("程序退出")

# 启动鼠标监听器(放在线程中避免阻塞)
mouse_listener = Listener(on_click=on_click)
mouse_listener.start()

# 启动键盘监听器并阻塞主线程
with KeyboardListener(on_press=on_key_press) as keyboard_listener:
    keyboard_listener.join()

关键修改说明

  • 替换触发逻辑:移除原键盘'+'键的启停控制,改为监听鼠标左键的按下(pressed=True)和释放(pressed=False)事件,分别对应启动和停止自动点击
  • 双监听器处理:同时保留键盘监听器以支持'-'键退出,将鼠标监听器放在独立线程中运行,避免主线程被阻塞
  • 逻辑对齐:将点击线程的start_clicking和stop_clicking方法直接绑定到鼠标左键的按住/松开动作,无需额外状态判断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 19:50:29