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

2024-05-15 02:51:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个程序正在运行循环。 例如,每当我按下键盘上的“ESC”键时,它应该会调用一个函数来打印“You pressed the key 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)

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


Tags: keyimport命令程序youtruesys按键
2条回答

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

因为程序使用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

相关问题 更多 >

    热门问题