0

How do I get a user keyboard input with python and print the name of that key ?

e.g:

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

for better understanding i'm using pygame libary. and i built setting controller for my game. its worked fine but i'm able to use only keys on my dict. i dont know how to add the other keyboard keys.

see example:

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               

This is a part of my class. in my script i loading all related object to that class. the related object are the optional keys in the game.

e.g

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,

then in game loop:

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

The code worked perfectly but i trully dont know how to add keys that not letters and numbers such as "ENTER","SPACE" etc.

benny hassan
  • 101
  • 6
  • _"SPACE" ( and not " ")_, how did you get that output? what libraries are you using? – Matiiss Dec 23 '21 at 10:49
  • [This](https://stackoverflow.com/questions/24072790/how-to-detect-key-presses) maybe useful. – holydragon Dec 23 '21 at 10:50
  • wrong example. i built a dictionary where a-z, 0-9 are keys and GUI keyboard are the value. when user event == unicode - i'm using this dict and its worked fine . but i want to add the other keys from keyboard to my dictionary i deleeted this example if it can confuse – benny hassan Dec 23 '21 at 10:52
  • you can [edit] your question and also what GUI? provide a [mre] – Matiiss Dec 23 '21 at 10:52
  • @holydragon for keyboard libary i got to tell the program which key it is. i want just to take that name of that key – benny hassan Dec 23 '21 at 10:56
  • you still haven't told what GUI library you are using nor have you provided a [mre], also there are keycodes that can be used to tell which key was pressed, also `keyboard` definitely can tell you the name of the key – Matiiss Dec 23 '21 at 10:58
  • @matiss i'm working with pygame and i built a controller settings. i thought my question is general and not require a reproducible example. but its seems i got to do so so i will edit my question and add that example – benny hassan Dec 23 '21 at 10:59

3 Answers3

1

pygame provides a function for getting the name of the key pressed:

pygame.key.name

And so you can use it to get the name of the key, there is no need to use a dictionary for this:

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)
Matiiss
  • 5,970
  • 2
  • 12
  • 29
0
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
Robin Sage
  • 969
  • 1
  • 8
  • 24
0

Use keyboard module

import keyboard

while True: 
    print(f"You pressed {keyboard.get_hotkey_name()})
Ali FGT
  • 55
  • 8