[英]How to call a function whenever a key is pressed in 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.
每当我按下键盘上的“ESC”键时,它应该调出一个打印“你按下ESC键”的功能,也可能执行一些命令。
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. 在我所有尝试之后,msvcrt似乎无法在python 3.3中工作或出于其他原因。 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. 但是它需要输入到命令控制台才能输入要注册的输入,但是我的循环在tkinter中运行,所以我仍然需要一种方法让它在检测到按键后立即执行某些操作。
Because your program uses the tkinter
module, binding is very easy. 因为您的程序使用
tkinter
模块,所以绑定非常简单。 You don't need any external modules like PyHook
. 您不需要任何外部模块,如
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. 不幸的是,这只能在
Tk()
窗口中使用。 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. 作为
event=None
的进一步解释,我们将其放入,因为master.bind
烦人地将密钥作为参数发送。 This is is fixed by putting event
as the parameter in the function. 这是通过将
event
作为参数放在函数中来解决的。 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
. 然后我们将
event
设置为默认值None
因为我们有一个使用相同回调的按钮,如果不存在,我们会得到一个TypeError
。
如果您正在寻找非基于窗口的库: http : //sourceforge.net/projects/pykeylogger/ 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.