python - 检测按键 python/pygame 的持续时间

标签 python pygame keypress

在我的程序中,我希望用户能够按住一个按钮。释放按钮后,我希望打印他们按下该键的持续时间。我一直在尝试使用 pygame 时钟功能,但遇到了一些麻烦。该程序在第一次按键时工作正常,但在以后的按键中记录按键之间的任何停机时间。任何帮助将不胜感激,这是我的代码:

import pygame
from pygame.locals import *
def main():
    key = 0
    pygame.init()

    self = pygame.time.Clock()

    surface_sz = 480

    main_surface = pygame.display.set_mode((surface_sz, surface_sz))

    small_rect = (300, 200, 150, 90)
    some_color = (255, 0, 0)

    while True:
        ev = pygame.event.poll()

        if ev.type == pygame.QUIT:
            break;
        elif ev.type == KEYUP:
            if ev.key == K_SPACE:       #Sets the key to be used
                key += 1                #Updates counter for number of keypresses
                while ev.type == KEYUP:
                    self.tick_busy_loop()
                    test = (self.get_time()/1000.0)
                    print "number: ", key, "duration: ", test 
                    ev = pygame.event.poll()



main()

最佳答案

您可以使用 keyboard这个库。
这是我制作的示例代码:

import keyboard, time
while True:
    a = keyboard.read_event()     #Reading the key
    if a.name == "esc":break      #Loop will break on pressing esc, you can remove that
    elif a.event_type == "down":  #If any button is pressed (Not talking about released) then wait for it to be released
        t = time.time()           #Getting time in sec
        b = keyboard.read_event() 
        while not b.event_type == "up" and b.name == a.name:  #Loop till the key event doesn't matches the old one
            b = keyboard.read_event()
        print('Pressed Key "'+ b.name + '" for ' + str(time.time()-t))

如果您正在寻找更多解决方案(针对 PygamePynput),那么您可以找到它们 on my answer on other related question.

关于python - 检测按键 python/pygame 的持续时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19912831/

相关文章:

c - 有没有办法检测是否按下了某个键?

java - GWT 按键过滤器

Python:读取较大数据(二进制模式)时 read() 出现问题

python - 使用 Jinja2 模板缩小 Flask 应用程序的 HTML 输出

python - 当我尝试移动 Pygame 时,玩家回到初始位置

python - 检测鼠标是否离开 Pygame 窗口

ruby - 暂停 "until"循环并等待按键继续 (Ruby)

python - Writing multiple JSON to CSV in Python - 字典到 CSV

python - 语法错误: invalid syntax href = 'http://maps.google.com' + href

python - 在pygame中播放音乐的简单代码不起作用