Search code examples
pythonkeyboard

How do you hold down keys using the "Keyboard" module in python?


I am creating a racing game AI, and am trying to get it to hold down keys rather than it just tapping the keys on the keyboard really fast, such as holding down "w" to accelerate rather than just feather tapping it. Is there any way to make the keyboard module in python press and hold down a key until a certain input is pressed(such as "del")? The Keyboard module: https://www.geeksforgeeks.org/keyboard-module-in-python/

This is what I have tried, but it just presses the button once, then waits until I press 'del' to end the program, and finish.

keyboard.press('w')
keyboard.wait('del')
keyboard.release('w')

Solution

  • Your thing of using keyboard.press('w') works, but it just doesn't show as it would when you hold a key. You can test this with some kind of game that uses "w" as a movement key, then running your script and you should move forwards for the said amount of time.