The Wayback Machine - https://web.archive.org/web/20240911133826/https://www.geeksforgeeks.org/how-to-get-keyboard-input-in-pygame/
Open In App

How to get keyboard input in PyGame ?

Last Updated : 08 Jun, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 occurring
    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:

pygamekey Description
K_BACKSPACE backspace
K_TAB tab
K_CLEAR clear
K_RETURN return
K_PAUSE pause
K_ESCAPE escape
K_SPACE space
K_EXCLAIM exclaim
K_HASH hash
K_QUOTEDBL quotedbl
K_DOLLAR dollar
K_AMPERSAND ampersand
K_QUOTE quote
K_LEFTPAREN left parenthesis
K_RIGHTPAREN right parenthesis
K_ASTERISK asterisk
K_PLUS plus sign
K_COMMA comma
K_MINUS  minus sign
K_PERIOD  period
K_SLASH forward slash
K_0  0
K_1 1
K_2 2
K_3 3
K_4 4
K_5 5
K_6 6
K_7 7
K_8 8
K_9 9
K_COLON colon
K_SEMICOLON semicolon
K_LESS less-than sign
K_EQUALS equals sign
K_GREATER greater-than sign
K_QUESTION  question mark
K_AT at
K_LEFTBRACKET left bracket
K_BACKSLASH  backslash
K_RIGHTBRACKET   right bracket
K_CARET caret
K_UNDERSCORE underscore
K_BACKQUOTE grave
K_a,b,c…….z A to Z Alphabet
K_DELETE delete
K_KP0, K_KP1, K_KP2….K_KP9 keypad 0 to 9
K_KP_PERIOD keypad period
K_KP_DIVIDE keypad divide
K_KP_MULTIPLY keypad multiply
K_KP_MINUS keypad minus
K_KP_PLUS   keypad plus
K_KP_ENTER keypad enter
K_KP_EQUALS keypad equals
K_UP up arrow
K_DOWN down arrow
K_RIGHT  right arrow
K_LEFT   Left arrow
K_INSERT Insert
K_HOME Home
K_END End
K_PAGEUP  Page Up
K_PAGEDOWN   Page Down
K_F1, K_F2, K_F3……K_F15 F1 to F15
K_NUMLOCK Numlock
K_CAPSLOCK Capsloack
K_SCROLLOCK Scrollock
K_RSHIFT Right shift
K_LSHIFT Left shift
K_RCTRL right control
K_LCTRL Left control
K_RALT  Right alt
K_LALT  Left alt
K_RMETA right meta
K_LMETA  left meta
K_LSUPER left Windows key
K_RSUPER  right Windows key
K_MODE mode shift
K_HELP Help
K_PRINT Print Screen
K_SYSREQ sysrq
K_BREAK Break
K_MENU Menu
K_POWER Power
K_EURO Euro

 

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 occurring
    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.



Previous Article
Next Article

Similar Reads

Adding Collisions Using pygame.Rect.colliderect in Pygame
Prerequisite: Drawing shapes in Pygame, Introduction to pygame In this article, we are going to use pygame.Rect.colliderect for adding collision in a shape using Pygame in Python. We can easily add collisions in Pygame shapes using the colliderect( ). For this, we are going to draw two rectangles then we will check if the rectangles are colliding o
3 min read
How to create a text input box with Pygame?
In this article, we will discuss how to create a text input box using PyGame. Installation Before initializing pygame library we need to install it. This library can be installed into the system by using pip tool that is provided by Python for its library installation. Pygame can be installed by writing these lines into the terminal. We can install
3 min read
Pygame - Input Handling
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. The sys module in Python provides various functions and variables that are used to manipulate different parts of the Python runtime environment. It allows oper
5 min read
PyQt5 QCalendarWidget -Grabbing Keyboard input
In this article we will see how we can grab the keyboard input for the QCalendarWidget. By grabbing keyboard the calendar will not be affected, except that it doesn't receive any keyboard events. setFocus moves the focus as usual, but the new focus widget receives keyboard events only after releaseKeyboard is called. In order to do this we will use
2 min read
PyQt5 QCalendarWidget - Releasing Grabbed Keyboard input
In this article we will see how we can ungrab i.e release the keyboard input for the QCalendarWidget. By grabbing keyboard the calendar will not be affected, except that it doesn't receive any keyboard events. setFocus moves the focus as usual, but the new focus widget receives keyboard events only after releaseKeyboard is called. Grabbing can be d
2 min read
Python VLC MediaPlayer – Enabling Keyboard Input
In this article, we will see how we can enable keyboard input handling the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediaPlayer object is the basic object in vlc module for playing the video. By
2 min read
Python Arcade - Handling Keyboard Input
In this article, we will discuss how to handle keyboard inputs in Python arcade module. In Arcade, you can easily check which keyboard button is pressed and perform tasks according to that. For this, we are going to use these functions: on_key_press()on_key_release() Syntax: on_key_press(symbol,modifiers)on_key_release (symbol, modifiers) Parameter
4 min read
How to get the size of PyGame Window?
In this article, we will learn How to get the size of a PyGame Window. Game programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI, and much more and it can be amazingly fun. In python, game programming is done in pygame and it is one of the
2 min read
How to add moving platforms in PyGame
Prerequisite: Drawing in Pygame In this article, we will learn how we can add moving platforms to our game using PyGame in Python. Creating a Platform We can easily create any type of platform in pygame using the draw( ) method. For this, we will create react with specific width and height using the draw.rect() function. Syntax: pygame.draw.rect(su
5 min read
Pygame - Surface
When using Pygame, surfaces are generally used to represent the appearance of the object and its position on the screen. All the objects, text, images that we create in Pygame are created using surfaces. Creating a surface Creating surfaces in pygame is quite easy. We just have to pass the height and the width with a tuple to pygame.Surface() metho
6 min read
Python | Display images with PyGame
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of the developer, what type of game he/she wants to develop using this toolkit. Command to install pygame : pip in
2 min read
Python | Display text to PyGame window
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of the developer, what type of game he/she wants to develop using this toolkit.. Command to install pygame on wind
6 min read
Python | Drawing different shapes on PyGame window
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit. Command to install pygame : pip instal
3 min read
Introduction to pygame
Game programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI, and much more and it can be amazingly fun. In python, game programming is done in pygame and it is one of the best modules for doing so. Installing pygame: Pygame requires Python;
5 min read
PyGame Set Mouse Cursor from Bitmap
In this article, we are going to see how to set the mouse cursor from bitmap using the PyGame module in Python. What is PyGame?It is a cross-platform set of Python modules designed for writing video games.It includes computer graphics and sound libraries designed to be used with the Python programming language.It can handle time, video, music, font
5 min read
How to create an empty PyGame window?
Pygame window is a simple window like any other window, in which we display our game screen. It is the first task we do so that we can display our output onto something. Our main goal here is to create a window and keep it running unless the user wants to quit. To perform these tasks first we need to install pygame package and import some pre-defin
2 min read
Python | Making an object jump in PyGame
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit. So, in this article, we will learn how
3 min read
Python | Playing audio file in Pygame
Game programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI and much more and it can be amazingly fun. In python, game programming is done in pygame and it is one of the best modules for doing so. Note: For more information, refer to Introdu
2 min read
Python - Moving an object in PyGame
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit. In this tutorial, we are going to lear
3 min read
Slide Puzzle using PyGame - Python
Slide Puzzle game is a 2-dimensional game i.e the pieces can only be removed inside the grid and reconfigured by sliding them into an empty spot. The slide puzzle game developed here is a 3X3 grid game i.e 9 cells will be there from 1 to 8(9 is not here since a blank cell is needed for sliding the neighboring cells). In this article, we are going t
15 min read
Python - Drawing design using arrow keys in PyGame
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit. In this article we will see how we can
3 min read
Bubble sort visualizer using PyGame
In this article we will see how we can visualize the bubble sort algorithm using PyGame i.e when the pygame application get started we can see the unsorted bars with different heights and when we click space bar key it started getting arranging in bubble sort manner i.e after every iteration maximum value element should come at last. Bubble Sort is
3 min read
Save/load game Function in Pygame
Pygame is a free-to-use and open-source set of Python Modules. And as the name suggests, it can be used to build games, and to save game data or the last position of the player you need to store the position of the player in a file so when a user resumes the game its game resumes when he left. In this case, the text file with JSON format stores the
4 min read
Pygame - Random Movement of Object
Prerequisite: How to draw rectangle in Pygame? In this article, we will learn how we can add random movements in objects using PyGame in Python. Random movement in a single object To add random movement in our object we are going to use randint method of the random module. Syntax: random.randint(a, b) Parameters: a and b : Two integers Returns: Ret
6 min read
How to initialize all the imported modules in PyGame?
PyGame is Python library designed for game development. PyGame is built on the top of SDL library so it provides full functionality to develop game in Python. Pygame has many modules to perform it's operation, before these modules can be used, they must be initialized. All the modules can be initialized individually or one at a time. This post desc
2 min read
Install Pygame in Linux
In this article, we will discuss how to install PyGame in the Linux system. We are using Ubuntu 20 LTS you can use any other one. To successfully install PyGame in your Linux system, follow the below procedure: First Check you are using python's latest version or not. Because the PyGame is only supported python 3.7.7 or higher version so make sure
2 min read
Collision Detection in PyGame
Prerequisite: Introduction to pygame Collision detection is a very often concept and used in almost games such as ping pong games, space invaders, etc. The simple and straight forward concept is to match up the coordinates of the two objects and set a condition for the happening of collision. In this article, we will be detecting a collision betwee
7 min read
Adding Boundary to an Object in Pygame
Boundaries to any game are very important. In snake games, space invaders, ping pong game, etc. the boundary condition is very important. The ball bounces at the boundaries of the screen in ping pong games. So, the idea behind this boundaries is to change the position of the ball or object in reverse direction as soon as it hits the wall. Let us se
5 min read
Interesting Facts about PYGAME
Pygame is a set of python module which is used in designing video games. In Pygame, there are computer graphics and sound libraries in order to develop high quality and user interactive games. Pygame was developed by Pete Shinners. Till 2000, it was a community project, later on it was released under open source free software General Public License
2 min read
Binary Search Visualization using Pygame in Python
An algorithm like Binary Search can be understood easily by visualizing. In this article, a program that visualizes the Binary Search Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in Python using pygame library. Approach Generate random array, sort it using any sorting algorithm, and fill the pygame window with ba
4 min read
Article Tags :
Practice Tags :