如何在屏幕上显示键盘?

How do I display a keyboard on-screen?

我的问题是我想向用户显示一个键盘,它显示键盘上的所有键并突出显示某些键。 为了我的目的,我想展示:

在我正在制作的程序中,黑键和白键可以作为钢琴键演奏。一些上下文是我已经在使用 pygame 来检测按键输入。

用户计算机上的键盘也各不相同。它可以是 qwerty azerty,具体取决于他们的硬件。

当我查看 pygame docs 时,它们只提供一般原语,例如绘制精灵、将它们分组等。我没有看到任何用于键盘的预烘焙资源。

可以使用 python 库 keyboardlayout 来做到这一点。 使用它可以显示 qwerty 或 azerty 布局,并且 this example 通过传入 overrides 参数突出显示特定键。它适用于 pygame 和 tkinter。

使用方法如下:

  1. 决定要显示的布局,qwertyazerty_laptop。即layout_name输入
  2. 确定您希望键盘有多大。您可以通过设置单个字母键的大小来控制大小,并且该大小(和填充输入)决定了整个键盘的大小。一个key的大小输入是letter_key_size,需要你传入(width_size_px, height_size_px).
  3. 决定你想要的键盘设置。具体来说,你想要它在哪里(x,y),它应该是什么颜色,它应该以像素为单位有什么填充?所有这些设置都存储在 KeyboardInfo class 实例中。请记住,在 pygame 中,(0, 0) 是左上角,x 向右增加,y 向下增加。
  4. 确定要使用哪些设置来显示键,具体而言:键之间的边距(以像素为单位)、背景颜色、文本颜色、字体以及从键边缘到文本的填充(以像素为单位)。所有这些信息都存储在 KeyInfo class 实例中。
  5. 实例化 KeyInfo、KeyboardInfo 并设置 letter_key_size 和 layout_name 后,您可以使用该信息来实例化实际的 KeyboardLayout class 实例。该实例包含您要绘制的键盘图像。也是pygame.sprite.Group so to display it we use the normal pygame method sprite_group.draw(screen).

将所有这些收集起来并付诸行动,我们得到:

import keyboardlayout as kl
import pygame

layout_name = 'qwerty'
pygame.init()

# set the letter key size in pixels
key_size = 60
grey = pygame.Color('grey')
# set the keyboard position and color info
keyboard_info = kl.KeyboardInfo(
    position=(0, 0),
    padding=2,
    color=~grey
)
# set the letter key color, padding, and margin info in px
key_info = kl.KeyInfo(
    margin=10,
    color=grey,
    txt_color=~grey,  # invert grey
    txt_font=pygame.font.SysFont('Arial', key_size//4),
    txt_padding=(key_size//6, key_size//10)
)
# set the letter key size info in px
letter_key_size = (key_size, key_size)  # width, height
keyboard_layout = kl.KeyboardLayout(
    layout_name,
    keyboard_info,
    letter_key_size,
    key_info
)
# set the pygame window to the size of the keyboard
screen = pygame.display.set_mode(
    (keyboard_layout.rect.width, keyboard_layout.rect.height))
screen.fill(pygame.Color('black'))

# draw the keyboard on the pygame screen
keyboard_layout.draw(screen)
pygame.display.update()

# loop until the user closes the pygame window
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.display.quit()
            running = False

pygame.quit()

以下是它的一些示例: