如何在不使用pygame的情况下检测按键事件和按键按下事件 [英] How to detect key press event and key hold down event without using pygame
问题描述
我目前正在寻找一个能够检测/监视键盘的库. 我的目的是检测何时按住某个键以及何时发生该键.
I am currently looking for a library that is able to detect/monitor the keyboard. My intention is to detect when a key is being held down and while it occurs something should happen.
大多数SO帖子都建议使用pygame,但我发现它太多了,无法包含诸如库这样的简单任务.我也尝试过使用pynput
,它只能检测到一台印刷机,而不是一堆印刷机.
Most SO posts suggest to use pygame, but i find it a bit too much, to involve a library such as that for this simple task. i've also tried with pynput
, which resulted only detecting one press rather than a stream of presses.
关于如何在循环检测按键的同时执行此操作的任何建议...
any suggestions on how i can make this while loop detect a key is being pressed / held down...
我尝试使用while循环:
My attempt with while loop:
from pynput import keyboard
def on_press(key):
while key == keyboard.Key.cmd_l:
try:
print('- Started recording -'.format(key))
except IOError:
print "Error"
else:
print('incorrect character {0}, press cmd_l'.format(key))
def on_release(key):
print('{0} released'.format(key))
if key == keyboard.Key.cmd_l:
print('{0} stop'.format(key))
keyboard.Listener.stop
return False
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
while解决方案使它陷入了while循环中,从而无法摆脱它.
The while solution make it stuck in the while loop, making it impossible to get out of it.
推荐答案
我发现的最简单的方法之一就是使用pynput模块.在这里也可以找到很好的例子
One of the simplest way I found is to use pynput module.can be found here with nice examples as well
from pynput import keyboard
def on_press(key):
try:
print('alphanumeric key {0} pressed'.format(
key.char))
except AttributeError:
print('special key {0} pressed'.format(
key))
def on_release(key):
print('{0} released'.format(
key))
if key == keyboard.Key.esc:
# Stop listener
return False
收集事件直到发布
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
上面是为我解决的示例,请安装并继续
sudo pip install pynput (pip3 if python3.*)
这篇关于如何在不使用pygame的情况下检测按键事件和按键按下事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!