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

2023-12-30

我有一个正在循环运行的程序。 例如,每当我按下键盘上的“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)

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


因为你的程序使用了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.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在Python中按下按键时调用函数 的相关文章

随机推荐