My problem is that I want to show a keyboard to users that shows all keys on the keyboard and highlights certain keys. For my purpose, I want to show:
The black and white keys will be playable as piano keys in a program that I'm working on. Some context is that I am already using pygame to detect key press input.
Also the keyboard that users have on t heir computer varies. It can be qwerty azerty depending upon their hardware.
When I looked into the pygame docs they only provide general primitives like drawing sprites, putting them in groups etc. I don't see any pre-baked resources for a keyboard.
One can do this by using the python library keyboardlayout. Using it one can show an qwerty or azerty layout and this example highlights specifc keys by passing in the overrides argument. It works with pygame and tkinter.
Here's how you use it:
qwerty
or azerty_laptop
. That is the layout_name inputletter_key_size
and it needs you to pass in (width_size_px, height_size_px).Gathering that all together and putting it into action we get:
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()