2

My issue is rather simple. I want to run a loop while the user holds down a key, in my case R.

The catch is: I don't want to use PyGame, and the console window will not be focused. (Selected)

Edit: I saw that this question was labeled a duplicate. I have checked the other thread, and the key difference between the two is that this one needs to check for a key to be held, with the python/console window out of focus and not selected.

Jacob Birkett
  • 1,767
  • 3
  • 23
  • 44

1 Answers1

0

In case you are using windows:

msvcrt is probably the library you are looking for (https://docs.python.org/2/library/msvcrt.html). This lib contains the kbhit function, which 'Return true if a keypress is waiting to be read':

from msvcrt import kbhit, getch

while (kbhit()):
    getch()
    #code

The getch reads the key, so it doesn't stay in the loop forever (because the kbhit function still detects a non-read key).

  • Thanks! One slight problem: It cant detect key press if the console window is out of focus. ```while True: if kbhit() and getch() == b'r':``` – Jacob Birkett Jul 18 '16 at 00:17