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:
Using
pygame
: (Good)It will only detect the keys that you will write in the code.
Use
pip install pynput
to installpynput
.Use
pip install pygame
to installpygame
.