- How to Detect Keypress in Python
- Detect Keypress Using the keyboard Module in Python
- Detect Keypress Using the is_pressed() function in Python
- Keypress using the read_key() Function
- Detect Keypress Using the wait() Function
- Conclusion
- Detect Keypress in Python
- Detect KeyPress Using the keyboard Module in Python
- Detect KeyPress Using the pynput Module in Python
- Related Article — Python Input
How to Detect Keypress in Python
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 the 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.
If you are working with Python 3, you can install the keyboard module using the following command.
Detect Keypress Using the is_pressed() function in Python
To detect the keypress in Python, 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 as shown in the following example.
import keyboard while True: if keyboard.is_pressed("a"): print("You pressed 'a'.") break
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.
Keypress using the read_key() Function
Instead of the is_pressed() function, we can use the read_key() function to detect the keypress in Python. 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
In the above example, if the user presses the key “a”, the read_key() method returns the character “a”. Hence, the statement inside the if block becomes True and the execution moves out of the while loop using the break statement. Otherwise, the program keeps waiting for the user to press the correct key.
Detect Keypress Using the wait() Function
We can also detect keypress using the wait() function defined in the keyboard module. The wait() function takes a character as input. Upon execution of the wait() method, the execution of the program is paused until the user presses the key passed as an input argument to the function. Once the user presses the correct key, the function stops its execution.
You can observe this in the following example.
import keyboard keyboard.wait("a") print("You pressed 'a'.")
In this example, we have passed the character “a” to the wait() method. Hence, the wait() method halts the execution of the program until the user presses the key “a”. Once the correct key is pressed, the execution of the program moves ahead and the print statement is executed.
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.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Detect Keypress in Python
- Detect KeyPress Using the keyboard Module in Python
- Detect KeyPress Using the pynput Module in Python
If you need access to the hardware like input devices such as the keyboard, there are modules available in Python which can make your lives much easier. Using such modules, you can easily perform the task you want without dealing with the complexities of the system.
In this article, you will learn how to detect keypress using modules in Python. There are many modules used to detect keypress in Python, and out of which, the two most popular and widely used modules are keyboard and pynput .
Detect KeyPress Using the keyboard Module in Python
The keyboard module allows us to take full control of the keyboard and comes with various predefined methods to choose from. These methods make it much easier for us to work with the keyboard and detect the user’s physical keypresses on the keyboard.
To install the keyboard module, execute the below command inside your command prompt or terminal.
First, you have to import the keyboard module into the program. Here, we are using three methods to detect keypress in Python read_key() , is_pressed() and on_press_key() .
import keyboard while True: if keyboard.read_key() == "p": print("You pressed p") break while True: if keyboard.is_pressed("q"): print("You pressed q") break keyboard.on_press_key("r", lambda _:print("You pressed r"))
You pressed p You pressed q You pressed r
The read_key() will read which key a user has pressed on the keyboard, and if it’s that key which you wanted, in this case, p , it will print the message You pressed p . The read_key() function returns a character.
The is_pressed() takes a character as an input, and if it matches with the key which the user has pressed, it will return True and False otherwise.
The on_press_key() takes two parameters as an input, the first is the character, and the second is the function. If the user presses the key that matches the key specified as the first parameter of the on_press_key() function, it will only execute the function you have passed in as the second parameter.
Detect KeyPress Using the pynput Module in Python
The pynput module is used to detect and control input devices, mainly mouse and keyboard. But in this tutorial, you will only see how to use this module for detecting keypress on the keyboard. Before using this module, you first have to install it using the command below.
To use this module for detecting keypress, you first have to import keyboard from pynput module.
from pynput import keyboard def on_press(key): try: print('Alphanumeric key pressed: '.format( key.char)) except AttributeError: print('special key pressed: '.format( key)) def on_release(key): print('Key released: '.format( key)) if key == keyboard.Key.esc: # Stop listener return False # Collect events until released with keyboard.Listener( on_press=on_press, on_release=on_release) as listener: listener.join()
Alphanumeric key pressed: a Key released: 'a' Alphanumeric key pressed: b Key released: 'b' special key pressed: Key.ctrl_l Key released: Key.ctrl_l
Note that the above output may vary depending upon which keys are pressed by the user.
To detect keypress, we are defining two functions, on_press and on_release . The function on_press will be executed when the user will press a button on the keyboard, and as soon as the user releases that button, the on_release function will be executed.
Both functions are only printing the keys pressed and released by the user to the console window. You can change the implementation of these two functions based on your requirements.
Then at the end, we have a Listener that will listen to the keyboard events, and it will execute the on_press and on_release functions accordingly.
Sahil is a full-stack developer who loves to build software. He likes to share his knowledge by writing technical articles and helping clients by working with them as freelance software engineer and technical writer on Upwork.