While creating programs that run with graphical user interfaces, we need to detect if the user has pressed a key or not several times. In this article, we will see how we can detect keypress in python.
Detect Keypress using Keyboard module in Python
To detect keypress in python, we can use the keyboard module. It works on both Windows and Linux operating systems and supports all the hotkeys. You can install the keyboard module in your machine using PIP as follows.
pip install keyboard
To detect keypress, we will use the is_pressed()
function defined in the keyboard module. The is_pressed()
takes a character as input and returns True
if the key with the same character is pressed on the keyboard. Therefore, we can use the is_pressed()
function with a while loop to detect keypress in python as shown in the following example.
import keyboard
while True:
if keyboard.is_pressed("a"):
print("You pressed 'a'.")
break
Output:
aYou pressed 'a'.
Here, we have executed the while loop until the user presses the key “a
”. On pressing other keys, the is_pressed()
function returns False
and the while loop keeps executing. Once the user presses “a”,
the condition inside if block becomes true and the break statement is executed. Hence the while loop terminates.
Instead of the is_pressed()
function, we can use use read_key()
function to detect the keypress. The read_key()
function returns the key pressed by the user. We can use the read_key()
function with a while loop to check whether the user presses a specific key or not as follows.
import keyboard
while True:
if keyboard.read_key() == "a":
print("You pressed 'a'.")
break
Output:
You pressed 'a'.
We can also detect keypress using the wait()
function defined in the keyboard module. The wait()
function takes a character as input. Upon execution, it keeps waiting until the user presses the key passed as an input argument to the function. Once the user presses the right key, the function stops its execution. You can observe this in the following example.
import keyboard
keyboard.wait("a")
print("You pressed 'a'.")
Output:
You pressed 'a'.
Conclusion
In this article, we have discussed different ways to detect keypress in python using the keyboard module. To learn more about inputs,you can read this article on getting user input from keyboard in python. You might also like this article on string concatenation in python.
The post How to Detect Keypress in Python appeared first on PythonForBeginners.com.