如何在python中按下键时调用函数

时间:2013-10-31 13:17:21

标签: python

我有一个运行循环的程序。 每当我按下键盘上的“ESC”键时,它应该调出一个打印“你按下ESC键”的功能,也可以执行一些命令。

我试过了:

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()

经过我的所有尝试,msvcrt似乎无法在python 3.3中工作或出于其他原因。 基本上,如何让我的程序在程序运行的任何时候对任何按键做出反应?

编辑:另外,我发现了这个:

import sys

while True:
    char = sys.stdin.read(1)
    print ("You pressed: "+char)
    char = sys.stdin.read(1)

但是它需要输入才能输入到命令控制台中以便重新注册输入,但是我的循环在tkinter中运行,因此我仍然需要一种方法让它在检测到按键后立即执行某些操作。 / p>

2 个答案:

答案 0 :(得分:1)

因为您的程序使用tkinter模块,所以绑定非常简单。 您不需要任何外部模块,如PyHook

例如:

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

不幸的是,这只能在Tk()窗口中使用。此外,在键绑定期间应用回调时,您不能指定任何参数。

作为对event=None的进一步解释,我们将其放入,因为master.bind恼人地将密钥作为参数发送。通过将event作为参数放在函数中来解决此问题。然后,我们将event设置为默认值None,因为我们有一个使用相同回调的按钮,如果不存在,我们会得到TypeError

答案 1 :(得分:0)

如果您正在寻找基于非窗口的库:http://sourceforge.net/projects/pykeylogger/