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.
#Using pynput
module: (Best)
You can use this code:
from pynput import keyboard
import time
def on_key_release(key): #what to do on key-release
time_taken = round(time.time() - t, 2) #rounding the long decimal float
print("The key",key," is pressed for",time_taken,'seconds')
return False #stop detecting more key-releases
def on_key_press(key): #what to do on key-press
return False #stop detecting more key-presses
with keyboard.Listener(on_press = on_key_press) as press_listener: #setting code for listening key-press
press_listener.join()
t = time.time() #reading time in sec
with keyboard.Listener(on_release = on_key_release) as release_listener: #setting code for listening key-release
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With