Determine length of keypress in python

2020-02-09 14:37发布

Suppose that I want to make a very simply program in python that indicates how long a key is pressed. So if I type and hold the j key for a few moments, I am looking to write a program capable of displaying information like the key 'j' was pressed for 1.1 seconds.

From what I understand, the way this should be achieved is by detecting and timestamping the KEYDOWN events and KEYUP events, and making appropriate subtractions of timestamps. So it would suffice to detect KEYDOWN and KEYUP events.

There are a wide variety of questions and answers on SO concerning detecting a single keypress or about detecting single character input, such as this one or this one, which both use some form of getch. I've looked at the python curses library, and from what I can tell the primary form of key detection is also in the form of single-character getch(). But these do not detect the length of keypress --- they only detect KEYDOWN.

I recognize that detecting the length of a keypress is a necessary task in gaming, and so I expect that pygame has methods to detect keypress duration. But I would hope that it is possible to use a much slimmer and more direct library to detect keypress duration.

1条回答
Emotional °昔
2楼-- · 2020-02-09 15:22

Using pynput module: (Best)

You can use this code:

from pynput import keyboard 
import time

def callb(key): #what to do on key-release
    ti1 = str(time.time() - t)[0:5] #converting float to str, slicing the float
    print("The key",key," is pressed for",ti1,'seconds')
    return False #stop detecting more key-releases
def callb1(key): #what to do on key-press
    return False #stop detecting more key-presses

with keyboard.Listener(on_press = callb1) as listener1: #setting code for listening key-press
    listener1.join()

t = time.time() #reading time in sec

with keyboard.Listener(on_release = callb) as listener: #setting code for listening key-release
    listener.join()

Using pygame: (Good)

import time
import pygame
import os
os.environ["SDL_VIDEO_CENTERED"] = "1"

screen = pygame.display.set_mode((600, 600))
pygame.display.set_caption("Time")
clock = pygame.time.Clock()

pygame.init()

clock = pygame.time.Clock()

running = True       
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            pygame.quit()
            break
        if event.type == pygame.KEYDOWN:
            # detect key 'a'
            if event.key == pygame.K_a: # key 'a'
                t = time.time()
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_a: # key 'a'
                t = time.time() - t; t = str(t); t = t[:5]
                print("You pressed key 'a' for",t,'seconds')


        screen.fill((255, 255, 255))
        pygame.display.update()

        clock.tick(40)

It will only detect the keys that you will write in the code.

Use pip install pynput to install pynput.
Use pip install pygame to install pygame.

查看更多
登录 后发表回答