I am trying to find a way to get KeyDown and KeyUp events in Python. With Pygame, this is easily done with pygame.KEYDOWN
and pygame.KEYUP
, but I am trying to find a way to do it without using a GUI.
Ideally, I would like to be able to define a function isKeyDown(key)
, which would return True
if key
is currently being held down, or return False
if it isn't, but either way, it would move on with the code (it would be non-blocking). For example:
while True:
if not isKeyDown("a"): #If 'a' isn't currently being pressed
print ("You are not pressing 'a'")
elif isKeyDown("a"): #If 'a' is being held down when this is run
print ("You are pressing 'a'")
print ("This is the end of this program")
break
I've tried msvcrt.getch()
, but that has two problems:
1) It stops the program until something is pressed, and
2) It doesn't really tell you if the key is being held down; it simply returns if the key is being pressed at the time. This can sometimes coincide since Windows repeats key presses when they are held down, but it is unlikely to happen when the while
loop is being run at maximum speed.
I've also used msvcrt.kbhit()
, but it sets itself to 1
if any key has been pressed and not read by msvcrt.getch()
, and so that still runs into the problems of msvcrt.getch()
and doesn't really return whether a key is actually currently being held down.
I am using Windows, so the curses
module that many people have used to answer similar questions isn't available.
Is there a way to define such a isKeyDown()
function in Windows without a GUI, preferably only using built-in modules? If this is not possible with the built-in Python modules, third-party modules would be okay, as long as they don't require a GUI.
Even using Pygame or Tkinter would be fine, as long as a way to turn off their GUIs.
If this is not possible, please tell me why, so I can stop looking for a solution (I have been trying to do little else for the past few days).
I am using Python 3.5.2 on a 64-bit Windows 10 laptop.