问题描述
在我开发的游戏中,我想检测NUMLOCK
按键 (或 keyup ),例如注册回调"功能.
In a game I'm developing, I want to detect a NUMLOCK
keypress (or keyup), like registering a "callback" function when it gets pressed.
我不要求在给定的时刻我已经可以做到,也没有兴趣更改其值.这是关于在按键发生时知道的信息,因此我不必每十分之一秒就轮询一次其状态.
I'm not asking to read its state in a given moment, I can do that already, nor I'm interested in changing its value. It's about being aware of the keypress when it happens so I don't have to poll its state every tenth of a sec or so.
该游戏使用curses
,当前使用的是getch()
. Curses不能检测到NUMLOCK
按键,而且我从未想到过(与LED相关的键盘不会产生"任何按键),我想知道是否有任何办法比取代主要的curses更好.循环访问非阻塞getch()
并调用keyboard_leds()
函数以读取当前状态.
The game uses curses
, and currently a blocking getch()
. Curses does not detect NUMLOCK
keypresses, and I never expected it to (led-related keyboard don't "produce" any key), and I wonder if there is any way to do so that is better than than replacing the main curses loop with a non-blocking getch()
and call a keyboard_leds()
function to read current state.
例如:我可以在初始化curses之后启动新线程,将其stdscr
屏幕作为参数传递,并且该线程将注册用于注册NUMLOCK
按键事件的回调函数(例如special_keypress()
) .因此,该函数仅在需要时调用keyboard_leds()
,然后更新stdscr
.
For example: I could start a new thread after initializing curses, passing its stdscr
screen as argument, and that thread would register register a callback function (say, special_keypress()
) for the event of a NUMLOCK
keypress. Thus, that function would only invoke keyboard_leds()
when needed, and then update stdscr
.
我不确定这是否可行,并且我知道我可能不得不考虑一些与体系结构相关的内容(内核/X11等),因此,如果没有跨平台的解决方案,可能的话,那么我只使用Linux即可.
I'm not sure if this is possible, and I'm aware that I'll probably have to go down to some architecture-dependent stuff (kernel/X11, etc), so if a cross-platform solution is not possible, then I'm fine with a Linux-only one.
推荐答案
好的,这就像使用蒸汽锤来破解螺母(特别是如果您正在创建类似CLI流氓的游戏),但是Pyglet至少获得了NUMLOCK我无法使它与CAPSLOCK
或SCROLLLOCK
一起使用,但是我的系统热键在所有可能的方式上都被覆盖了很多,所以可能就是我.
OK, it's like using a steam-hammer to crack nuts (especially if you are creating a CLI rogue-like game), but Pyglet gets the at least NUMLOCK keypresses in OS X. I couldn't make it work with either CAPSLOCK
or SCROLLLOCK
though, but my system hotkeys are pretty much overriden in every way possible, so it may be just me.
您可以尝试测试一下是否更适合您,然后查看Pyglet如何检测到这些密钥.
You could try and test if it works better for you, and then look at how Pyglet detects these keys.
import pyglet
from pyglet.window import key
window = pyglet.window.Window()
@window.event
def on_key_press(symbol, modifiers):
if symbol == key.NUMLOCK:
print 'NumLock was pressed, yay!'
elif symbol == key.CAPSLOCK:
print 'CapsLock was pressed, yay!'
elif symbol == key.SCROLLLOCK:
print 'ScrollLock was pressed, yay!'
@window.event
def on_draw():
window.clear()
if __name__ == '__main__':
pyglet.app.run()
这篇关于在Python中检测NUMLOCK/CAPSLOCK/SCRLOCK按键/键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!