这是一个 Pyglet 版本,您可以这样做。
我基于 common GUI class that I use often here on SO 编写它,因为它是模块化的并且更易于构建,而代码在 40 行之后不会变得混乱。
import pyglet
from pyglet.gl import *
key = pyglet.window.key
class main(pyglet.window.Window):
def __init__ (self):
super(main, self).__init__(800, 800, fullscreen = False)
self.x, self.y = 0, 0
#self.bg = Spr('background.jpg')
self.output = pyglet.text.Label('',
font_size=14,
x=self.width//2, y=self.height//2,
anchor_x='center', anchor_y='center')
self.alive = 1
self.pressed = []
self.key_table = {213 : 'a'}
def on_draw(self):
self.render()
def on_close(self):
self.alive = 0
def on_key_release(self, symbol, modifiers):
if symbol == key.LCTRL:
pass # Again, here's how you modify based on Left CTRL for instance
## All key presses represents a integer, a=97, b=98 etc.
## What we do here is have a custom key_table, representing combinations.
## If the sum of two pressed matches to our table, we add that to our label.
## - If no match was found, we add the character representing each press instead.
## This way we support multiple presses but joined ones still takes priority.
key_values = sum(self.pressed)
if key_values in self.key_table:
self.output.text += self.key_table[key_values]
else:
for i in self.pressed:
self.output.text += chr(i)
self.pressed = []
def on_key_press(self, symbol, modifiers):
if symbol == key.ESCAPE: # [ESC]
self.alive = 0
elif symbol == key.LCTRL:
pass # Modify based on left control for instance
else:
self.pressed.append(symbol)
def render(self):
self.clear()
#self.bg.draw()
self.output.draw()
self.flip()
def run(self):
while self.alive == 1:
self.render()
# -----------> This is key <----------
# This is what replaces pyglet.app.run()
# but is required for the GUI to not freeze
#
event = self.dispatch_events()
x = main()
x.run()
它可能看起来像很多代码,尤其是对于 Pygame 的答案。但是您也可以将其压缩到大约 15 行,但是如果您尝试进一步构建,代码会再次变得混乱。
希望这可行。现在我还没有考虑过这个数学..两个重复的键组合可能会产生与另一个键表示相同的值,只需将字典键 213 替换为元组键,例如 @ 987654324@ 代表 k+j
几个好处:
- 无需跟踪延迟
- 快速响应
- 任何键都可以转换为修饰符或映射自定义键盘布局,这意味着您可以将 QWERTY 转换为 DWORAK 仅用于此应用程序。不知道为什么要这样做,但是嘿.. 不关我的事 :D
- 覆盖默认键盘输入,因此您可以截取它们并使用它们做任何您想做的事情。
编辑:一个很酷的功能是注册每个键,但用连接的组合替换最后一个字符。这也是所有手动工作,因为键盘不是用来做双键表示的,而且它更多一个图形的想法..但会很酷:)