我正在编写一个打字程序,其中包含的字符比标准键盘上可用的字符多得多。为了实现这一目标,我需要将一些字母键转换为修饰键 CTRL+A。例如 f+j 将输出 a
。输入 f 然后输入 j 对于用户来说很慢,我需要他们能够按 f 和 j同时并接收一个输出。如果在程序运行时停止键盘的某些正常功能,那很好(甚至更好)。
我研究过pygame Keydown,但它似乎只有增加按键重复的功能,而没有停止按键输出的功能。 Pyglet 也是一种可能性,但它没有关于如何制作额外修饰键的确切文档。我能想到的唯一方法是不断扫描整个键盘以查看是否按下了任何键,但这不会确定按下键的顺序,并且会为用户创建错误,因为用户按下 f 然后j 的读法与用户按 j 然后 f 的读法相同,我只需要 f 然后 j 组合即可被系统理解为击键。
最佳答案
这是一个 Pyglet 版本,告诉你如何做到这一点。
我是根据常见的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
例如使用元组键,如 self.key_table = {(107, 106) : 'a'}
代表 k+j
一些好处:
- 无需跟踪延迟
- 快速响应
- 任何键都可以变成修改器或针对自定义键盘布局的映射,这意味着您可以仅针对此应用程序将 QWERTY 变成 DWORAK.. 不知道为什么您会想要这样,但是嘿.. 不关我的事 :D里>
- 覆盖默认键盘输入,以便您可以拦截它们并对其执行任何您想要的操作。
编辑:一个很酷的功能是注册每个键,但用连接的组合替换最后一个字符。同样,这都是手动工作,因为键盘并不意味着进行双键表示,而且它更多一个图形化的想法..但是会很酷:)
关于python - 如何对双击按键进行编程以使非修饰键在程序中的行为类似于修饰键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41465246/