[英]How to call a function whenever a key is pressed in 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中運行,所以我仍然需要一種方法讓它在檢測到按鍵后立即執行某些操作。
因為您的程序使用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
。
如果您正在尋找非基於窗口的庫: http : //sourceforge.net/projects/pykeylogger/ 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.