Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 912
user2919805 Avatar asked Oct 31 '13 13:10

user2919805


1 Answers

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.

like image 69
anon582847382 Avatar answered Oct 11 '22 21:10

anon582847382