Determine python keystroke length

Suppose I want to make a very simple program in python that shows how long a key has been pressed. Therefore, if I type and hold the j key for several seconds, I am looking to write a program that can display information like the key 'j' was pressed for 1.1 seconds .

From what I understand, the way this needs to be achieved is to detect and temporarily bind KEYDOWN events and KEYUP events and create the appropriate deductions for timestamps. Thus, it would be sufficient to detect the KEYDOWN and KEYUP events.

There are many different questions and answers to SO about detecting a single keystroke or about detecting a single character input, such as this or this one that uses some form of getch. I looked at the curses python library, and from what I can tell, the primary form of key detection is also presented as a single-character getch (). But they do not detect the length of the keystroke - they only detect KEYDOWN.

I understand that determining the length of a keystroke is a necessary task in games, and therefore I expect pygame to have methods for detecting the length of a keystroke. But I hope that you can use a much thinner and more direct library to detect the duration of a keystroke.

+5
source share
1 answer

Using the pynput module: (Best)

You can use this code:

 from pynput import keyboard import time def callb(key): #what to do on key-release ti1 = time.time() - t ti1 = str(ti1) #converting float value to string ti2 = ti1[0:5] #cutting the seconds ( time ) , without it , it will print like 0.233446546 print("The key",key,"Pressed For",ti2,'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() with keyboard.Listener(on_release = callb) as listener: #setting code for listening key-release listener.join() 

Note:

I'm not sure if pynput is a built-in module, if you get a ModuleNotFoundError , then use pip to install it:
pip install pynput

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) 

Note:

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

+1
source

Source: https://habr.com/ru/post/1259883/


All Articles