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

时间:2013-11-11 18:01:21

标签: 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()

2 个答案:

答案 0 :(得分:1)

我建议使用get_ticks()代替get_time()。您应该阅读有关差异的内容,但我觉得它可能无法正常工作,因为您没有明确地调用self.tick()

问题是您的代码输出了每个KEYUP事件之间的时间。还有另一种方法可以使代码工作,方法是在每个循环中遍历事件一次并继续向前,而不使用嵌套的while循环。

time_down = 0.0
time_elapsed = 0.0

while True:
    for ev in pygame.event.get():
        if ev.type == QUIT:
            break # you had a semicolon here, there is no need for it
        elif ev.type == KEYDOWN:
            if ev.key == K_SPACE:
                time_down = pygame.time.get_ticks()
        elif ev.type == KEYUP:
            if ev.key == K_SPACE:
                key += 1
                time_elapsed = (pygame.time.get_ticks() - time_down)/1000.0
                print "number: ", key, "duration: ", time_elapsed

    self.tick()
    pygame.display.update()

答案 1 :(得分:1)

您可以为此使用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))

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