I have a program that is running a loop. Whenever I press, for example, the key "ESC" on keyboard, it should call out a function which prints "You pressed the key ESC" and maybe executes some commands too.
I tried this:
from msvcrt import getch
while True:
key = ord(getch())
if key == 27: #ESC
print("You pressed ESC")
elif key == 13: #Enter
print("You pressed key ENTER")
functionThatTerminatesTheLoop()
After all my tries, msvcrt doesnt seem to work in python 3.3 or for whatever other reason. Basically, how do I make my program react to any keypress at any point of the time while the program is running?
EDIT: Also, I found this:
import sys
while True:
char = sys.stdin.read(1)
print ("You pressed: "+char)
char = sys.stdin.read(1)
But it requires enter to be entered into the command console for the input to be reistered, but I have my loop running in a tkinter, so I still need a way for it to do something immediately after the keypress is detected.
Because your program uses the tkinter
module, binding is very easy.
You don't need any external modules like PyHook
.
For example:
from tkinter import * #imports everything from the tkinter library
def confirm(event=None): #set event to None to take the key argument from .bind
print('Function successfully called!') #this will output in the shell
master = Tk() #creates our window
option1 = Button(master, text = 'Press Return', command = confirm)
option1.pack() #the past 2 lines define our button and make it visible
master.bind('<Return>', confirm) #binds 'return' to the confirm function
Unfortunately, this will only work in a Tk()
window. Also, when applying the callback during the key binding, you can't specify any arguments.
As a further explanation of event=None
, we put it in because master.bind
annoyingly sends the key as an argument. This is is fixed by putting event
as the parameter in the function. We then set event
to the default value None
because we have a button that uses the same callback, and if it wasn't there we would get a TypeError
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With