Afonso
Afonso

Reputation:

Python - Detect keypress

I have an application and I want whenever the user presses RETURN/ENTER it goes to a def with an input.

I am using this code:

while True:
    z = getch()
    # escape key to exit
    if ord(z) == 9:
        self.command()
        break
    if ord(z) == 27:
        print "Encerrando processo.."
        time.sleep(2)
        sys.exit()
        break

But it just blocks there and If I have more code it won't run it, only if the while is broken. I can't use tkinter either!

Is there anything that only runs if the key is pressed? Without looping.

Upvotes: 5

Views: 18949

Answers (2)

DJ8X
DJ8X

Reputation: 395

One of the ways that you could do it is to create a new thread to run the key detector. Here's an example:

import threading

class KeyEventThread(threading.Thread):
    def run(self):
        # your while-loop here

kethread = KeyEventThread()
kethread.start()

Note that the while loop will not run until you call the thread's start() function. Also, it will not repeat the function automatically - you must wrap your code in a while-loop for it to repeat.

Do not call the thread's run() function explicitly, as that will cause the code to run in-line with all of the other code, not in a separate thread. You must use the start() function defined in threading.Thread so it can create the new thread.

Also note: If you plan on using the atexit module, creating new threads will make that module not work correctly. Just a heads-up. :)

I hope this helped!

Upvotes: 6

cptroot
cptroot

Reputation: 319

It sounds like what you're looking for is a while loop based off of the input. If you put a list of desired states into an array, then you can check the input each time to see if it is one of the inputs you are trying to catch.

z = getch()
chars = [9, 27]
while ord(z) not in chars:
  z = getch()

if ord(z) == 9:
  do_something()
if ord(z) == 27:
  do_something_else()

do_more_things()

Upvotes: 0

Related Questions