用户键键盘输入

User key keyboard input

如何使用 python 获取用户键盘输入并打印该键的名称?

例如:

user clicked on "SPACE" and output is "SPACE" user clicked on "CTRL" and output is "CTRL".

为了更好地理解我正在使用 pygame 库。我为我的游戏构建了设置控制器。它工作正常,但我只能在我的字典上使用键。我不知道如何添加其他键盘键。

参见示例:

class KeyboardSettings():
    def __init__(self,description,keyboard):
        self.keyboard = keyboard
        self.default = keyboard
        self.description = description
        self.active = False

    def activate_change(self,x,y):
        fixed_rect = self.rect.move(x_fix,y_fix)
        pos = pygame.mouse.get_pos()

        if fixed_rect.collidepoint((pos)):
            if pygame.mouse.get_pressed()[0]:
                self.active = True   
        elif pygame.mouse.get_pressed()[0]:
                self.active = False               

这是我的一部分 class。在我的脚本中,我将所有相关对象加载到 class。相关对象是游戏中的可选键。

例如

SHOOT1 = KeyboardSettings("SHOOT","q")
move_right = KeyboardSettings("move_right","d")
#and more keys 

key_obj_lst = [SHOOT1,move_right....]

#also i built a dict a-z, 0,9
dict_key = { 'a' : pygame.K_a,
             'b' : pygame.K_b,
             'c' : pygame.K_c,
              ...
             'z' : pygame.K_z,
              
             '0' : pygame.K_0,
             ...
             '1' : pygame.K_1,
             '9' : pygame.K_9,

然后在游戏循环中:

for event in pygame.event.get():
   if event.type == pygame.KEYDOWN:
     for k in key_obj_lst:
     #define each key by user 
        if k.active:
            k.keyboard  = event.unicode
            default = False

         if k.keyboard in dict_key:
            if event.key == dict_key[k.keyboard]:
               if k.description == 'Moving Right':
                    moving_right = True
               if k.description == 'SHOOT':
                            SHOOT = True

代码运行完美,但我真的不知道如何添加不是字母和数字的键,例如“ENTER”、“SPACE”等

pip install keyboard

import keyboard  #use keyboard module
while True: 
    if keyboard.is_pressed('SPACE'): 
        print('You pressed SPACE!')
        break
    elif keyboard.is_pressed("ENTER"):
        print("You pressed ENTER.")
        break

使用keyboard模块

import keyboard

while True: 
    print(f"You pressed {keyboard.get_hotkey_name()})

pygame 提供获取按键名称的函数:

pygame.key.name

所以你可以用它来获取密钥的名称,不需要为此使用字典:

import pygame


pygame.init()
screen = pygame.display.set_mode((500, 400))


while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit()
        if event.type == pygame.KEYDOWN:
            key_name = pygame.key.name(event.key)
            print(key_name)