Skip to content
Related Articles

Related Articles

Improve Article

How to get keyboard input in PyGame ?

  • Last Updated : 30 Aug, 2021

While using pygame module of Python, we sometimes need to use the keyboard input for various operations such as moving a character in a certain direction. To achieve this, we have to see all the events happening. Pygame keeps track of events that occur, which we can see with the events.get() function. In this article, we are going to discuss how we can get and use various keyboard inputs in pygame.

Detecting if a key is pressed:

Whenever a key is pressed or released, pygame.event() queue methods pygame.KEYDOWN and pygame.KEYUP events respectively.

For example, if we want to detect if a key was pressed, we will track if any event of pygame.KEYDOWN occurred or not and, accordingly, we will get to know if any key was pressed or not. The code for detecting if any key was pressed or not can be written as:

Python




# importing pygame module
import pygame
 
# importing sys module
import sys
 
# initialising pygame
pygame.init()
 
# creating display
display = pygame.display.set_mode((300, 300))
 
# creating a running loop
while True:
       
    # creating a loop to check events that
    # are occuring
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
         
        # checking if keydown event happened or not
        if event.type == pygame.KEYDOWN:
           
            # if keydown event happened
            # than printing a string to output
            print("A key has been pressed")

 
 



Output:

 

After running this code, it is seen that whenever a key has pressed a string “A key has been pressed” is printed on the terminal

Detecting which key was pressed:

To know which key was pressed, we have to check the event.key variable corresponds to which pygame keys. For example, the pygame key for the letter “A” is “K_a” then we will compare event.Key with K a and if it comes to be same that means the key “A” was pressed.

 

The various keyboard key and corresponding pygame keys are:

pygamekeyDescription
K_BACKSPACEbackspace
K_TABtab
K_CLEARclear
K_RETURNreturn
K_PAUSEpause
K_ESCAPEescape
K_SPACEspace
K_EXCLAIMexclaim
K_HASHhash
K_QUOTEDBLquotedbl
K_DOLLARdollar
K_AMPERSANDampersand
K_QUOTEquote
K_LEFTPARENleft parenthesis
K_RIGHTPARENright parenthesis
K_ASTERISKasterisk
K_PLUSplus sign
K_COMMAcomma
K_MINUS minus sign
K_PERIOD period
K_SLASHforward slash
K_0 0
K_11
K_22
K_33
K_44
K_55
K_66
K_77
K_88
K_99
K_COLONcolon
K_SEMICOLONsemicolon
K_LESSless-than sign
K_EQUALSequals sign
K_GREATERgreater-than sign
K_QUESTION question mark
K_ATat
K_LEFTBRACKETleft bracket
K_BACKSLASH backslash
K_RIGHTBRACKET  right bracket
K_CARETcaret
K_UNDERSCOREunderscore
K_BACKQUOTEgrave
K_a,b,c…….zA to Z Alphabet
K_DELETEdelete
K_KP0, K_KP1, K_KP2….K_KP9keypad 0 to 9
K_KP_PERIODkeypad period
K_KP_DIVIDEkeypad divide
K_KP_MULTIPLYkeypad multiply
K_KP_MINUSkeypad minus
K_KP_PLUS  keypad plus
K_KP_ENTERkeypad enter
K_KP_EQUALSkeypad equals
K_UPup arrow
K_DOWNdown arrow
K_RIGHT right arrow
K_LEFT  Left arrow
K_INSERTInsert
K_HOMEHome
K_ENDEnd
K_PAGEUP Page Up
K_PAGEDOWN  Page Down
K_F1, K_F2, K_F3……K_F15F1 to F15
K_NUMLOCKNumlock
K_CAPSLOCKCapsloack
K_SCROLLOCKScrollock
K_RSHIFTRight shift
K_LSHIFTLeft shift
K_RCTRLright control
K_LCTRLLeft control
K_RALT Right alt
K_LALT Left alt
K_RMETAright meta
K_LMETA left meta
K_LSUPERleft Windows key
K_RSUPER right Windows key
K_MODEmode shift
K_HELPHelp
K_PRINTPrint Screen
K_SYSREQsysrq
K_BREAKBreak
K_MENUMenu
K_POWERPower
K_EUROEuro

 



For example, let’s create a code to check if key “A” or “J” or “P” or “M” was pressed or not. The code for checking will be: 

Python




# importing pygame module
import pygame
 
# importing sys module
import sys
 
# initialising pygame
pygame.init()
 
# creating display
display = pygame.display.set_mode((300, 300))
 
# creating a running loop
while True:
       
    # creating a loop to check events that
    # are occuring
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
         
        # checking if keydown event happened or not
        if event.type == pygame.KEYDOWN:
               
            # checking if key "A" was pressed
            if event.key == pygame.K_a:
                print("Key A has been pressed")
               
            # checking if key "J" was pressed
            if event.key == pygame.K_j:
                print("Key J has been pressed")
               
            # checking if key "P" was pressed
            if event.key == pygame.K_p:
                print("Key P has been pressed")
             
            # checking if key "M" was pressed
            if event.key == pygame.K_m:
                print("Key M has been pressed")

Output:

When we run this code and press the given keys the corresponding strings will be printed on the terminal.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :