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

Pygame如何在事件循环中实现鼠标长按持续触发事件

Pygame 鼠标长按自定义事件重复实现方案

你要的类键盘长按效果(首次触发→等待固定延迟→高速连续触发)不需要修改窗口初始化配置,也不需要依赖pygame.mouse.get_pressed()轮询,通过事件+时间戳做简单状态标记就能实现,逻辑完全可控,参数可以按需调整。

实现逻辑说明

  • 仅在原生MOUSEBUTTONDOWN事件触发时执行第一次操作,同时记录按下的按键、按下时间,标记进入长按等待状态
  • 原生MOUSEBUTTONUP事件触发时,清空所有长按状态,终止后续重复触发
  • 主循环中按帧检查长按状态:
    1. 等待阶段:判断当前时间距首次按下的时长是否达到你设置的初始延迟(比如你要的0.5秒),达到后切换为连续触发阶段,记录上一次重复触发的时间
    2. 连续触发阶段:判断当前时间距上一次重复触发的时长是否达到你设置的重复间隔(参考系统键盘默认值一般设为0.05~0.1秒即可),达到就执行一次目标操作,更新上次触发时间
  • 注意:pygame.key.set_repeat()仅对键盘事件生效,无法实现鼠标事件自动重复,不要误用该接口。

修改后的可运行代码

import pygame

# 长按配置参数 单位:毫秒
LONG_PRESS_INIT_DELAY = 500  # 首次触发后的等待延迟,对应你要的0.5秒
LONG_PRESS_REPEAT_INTERVAL = 100  # 延迟结束后连续触发的间隔,数值越小触发越快

WIDTH = 1000
HEIGHT = 800
WIN = pygame.display.set_mode((WIDTH, HEIGHT))

def main():
    pygame.init()
    run = True 
    clock = pygame.time.Clock()
    
    # 长按状态变量
    mouse_pressed = False
    pressed_button = None
    press_start_time = 0
    last_repeat_time = 0
    in_repeat_phase = False

    while run:
        clock.tick(60)
        current_time = pygame.time.get_ticks()
      
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                # 首次按下,立即触发一次,初始化长按状态
                print("鼠标按下,首次触发")
                mouse_pressed = True
                pressed_button = event.button
                press_start_time = current_time
                last_repeat_time = current_time
                in_repeat_phase = False
            if event.type == pygame.MOUSEBUTTONUP:
                # 松开按键,清空所有长按状态
                if event.button == pressed_button:
                    mouse_pressed = False
                    pressed_button = None
                    in_repeat_phase = False
        
        # 长按逻辑检测
        if mouse_pressed:
            if not in_repeat_phase:
                # 等待阶段,判断是否达到初始延迟
                if current_time - press_start_time >= LONG_PRESS_INIT_DELAY:
                    in_repeat_phase = True
                    last_repeat_time = current_time
                    # 进入重复阶段的第一次触发
                    print("长按延迟结束,开始连续触发")
            else:
                # 连续触发阶段,判断是否达到重复间隔
                if current_time - last_repeat_time >= LONG_PRESS_REPEAT_INTERVAL:
                    last_repeat_time = current_time
                    print("长按重复触发")

        WIN.fill((0, 0, 0))
        pygame.display.update()

    pygame.quit()

if __name__ == "__main__":
    main()

参数调整说明

  • 要修改首次触发后的等待时长,直接改LONG_PRESS_INIT_DELAY的数值即可
  • 要调整连续触发的速度,修改LONG_PRESS_REPEAT_INTERVAL即可,比如设为50就是每秒触发20次
  • 如果需要区分左右键不同的长按逻辑,加个判断pressed_button取值的分支就行,取值1对应鼠标左键、3对应鼠标右键、2对应中键

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 10:57:27