How to call a function whenever a key is pressed in python

I have a program that starts a loop. Whenever I press, for example, the β€œESC” key on the keyboard, it should call a function that prints β€œYou pressed the ESC key” and possibly executes some commands.

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 attempts, msvcrt does not seem to work in python 3.3 or for any other reason. Basically, how can I make my program respond to any keystroke at any given 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 to enter the input file, I need to enter the input into the console, but I have my loop running in tkinter, so I still need it to do something right after it detects a keypress.

+6
source share
2 answers

Since your program uses the tkinter module, binding is very simple. You do not need external modules, such as PyHook .

For instance:

 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 the Tk() window. In addition, when applying a callback during key binding, you cannot specify any arguments.

As an additional explanation of event=None we will add it because master.bind annoyingly passes the key as an argument. This is fixed by setting event as a parameter in the function. Then we set event to the default value of None , because we have a button that uses the same callback, and if it were not there, we would get a TypeError .

+1
source

If you are looking for a library other than Window: http://sourceforge.net/projects/pykeylogger/ .

0
source

Source: https://habr.com/ru/post/957123/


All Articles