pygame.key — pygame v2.4.0 documentation (2023)


pygame module to work with the keyboard


true if the display is receiving keyboard input from the system


get the state of all keyboard buttons


determine which modifier keys are being held


temporarily set which modifier keys are pressed


control how held keys are repeated


see how held keys are repeated

get the name of a key identifier


get the key identifier from a key name


start handling Unicode text input events


stop handling Unicode text input events


controls the position of the candidate list

This module contains functions for dealing with the keyboard.

The pygame.eventpygame module for interacting with events and queues queue gets pygame.KEYDOWN and pygame.KEYUPevents when the keyboard buttons are pressed and released. Both events havekey and mod attributes.

  • key: an integer ID representing every keyon the keyboard

  • mod: a bitmask of all the modifier keysthat were in a pressed state when the event occurred

The pygame.KEYDOWN event has the additional attributes unicode andscancode.

  • unicode: a single character string that is the fully translatedcharacter entered, this takes into account the shift and composition keys

  • scancode: the platform-specific key code, which could be different fromkeyboard to keyboard, but is useful for key selection of weird keys likethe multimedia keys

New in pygame 2.0.0: The pygame.TEXTINPUT event is preferred to the unicode attributeof pygame.KEYDOWN. The attribute text contains the input.

The following is a list of all the constants (from pygame.localspygame constants) used torepresent keyboard keys.

Portability note: The integers for key constants differ between pygame 1 and 2.Always use key constants (K_a) rather than integers directly (97) sothat your key handling code works well on both pygame 1 and pygame 2.

pygameConstant ASCII Description---------------------------------K_BACKSPACE \b backspaceK_TAB \t tabK_CLEAR clearK_RETURN \r returnK_PAUSE pauseK_ESCAPE ^[ escapeK_SPACE spaceK_EXCLAIM ! exclaimK_QUOTEDBL " quotedblK_HASH # hashK_DOLLAR $ dollarK_AMPERSAND & ampersandK_QUOTE quoteK_LEFTPAREN ( left parenthesisK_RIGHTPAREN ) right parenthesisK_ASTERISK * asteriskK_PLUS + plus signK_COMMA , commaK_MINUS - minus signK_PERIOD . periodK_SLASH / forward slashK_0 0 0K_1 1 1K_2 2 2K_3 3 3K_4 4 4K_5 5 5K_6 6 6K_7 7 7K_8 8 8K_9 9 9K_COLON : colonK_SEMICOLON ; semicolonK_LESS < less-than signK_EQUALS = equals signK_GREATER > greater-than signK_QUESTION ? question markK_AT @ atK_LEFTBRACKET [ left bracketK_BACKSLASH \ backslashK_RIGHTBRACKET ] right bracketK_CARET ^ caretK_UNDERSCORE _ underscoreK_BACKQUOTE ` graveK_a a aK_b b bK_c c cK_d d dK_e e eK_f f fK_g g gK_h h hK_i i iK_j j jK_k k kK_l l lK_m m mK_n n nK_o o oK_p p pK_q q qK_r r rK_s s sK_t t tK_u u uK_v v vK_w w wK_x x xK_y y yK_z z zK_DELETE deleteK_KP0 keypad 0K_KP1 keypad 1K_KP2 keypad 2K_KP3 keypad 3K_KP4 keypad 4K_KP5 keypad 5K_KP6 keypad 6K_KP7 keypad 7K_KP8 keypad 8K_KP9 keypad 9K_KP_PERIOD . keypad periodK_KP_DIVIDE / keypad divideK_KP_MULTIPLY * keypad multiplyK_KP_MINUS - keypad minusK_KP_PLUS + keypad plusK_KP_ENTER \r keypad enterK_KP_EQUALS = keypad equalsK_UP up arrowK_DOWN down arrowK_RIGHT right arrowK_LEFT left arrowK_INSERT insertK_HOME homeK_END endK_PAGEUP page upK_PAGEDOWN page downK_F1 F1K_F2 F2K_F3 F3K_F4 F4K_F5 F5K_F6 F6K_F7 F7K_F8 F8K_F9 F9K_F10 F10K_F11 F11K_F12 F12K_F13 F13K_F14 F14K_F15 F15K_NUMLOCK numlockK_CAPSLOCK capslockK_SCROLLOCK scrollockK_RSHIFT right shiftK_LSHIFT left shiftK_RCTRL right controlK_LCTRL left controlK_RALT right altK_LALT left altK_RMETA right metaK_LMETA left metaK_LSUPER left Windows keyK_RSUPER right Windows keyK_MODE mode shiftK_HELP helpK_PRINT print screenK_SYSREQ sysrqK_BREAK breakK_MENU menuK_POWER powerK_EURO EuroK_AC_BACK Android back button

The keyboard also has a list of modifier states (from pygame.localspygame constants) thatcan be assembled by bitwise-ORing them together.

pygameConstant Description-------------------------KMOD_NONE no modifier keys pressedKMOD_LSHIFT left shiftKMOD_RSHIFT right shiftKMOD_SHIFT left shift or right shift or bothKMOD_LCTRL left controlKMOD_RCTRL right controlKMOD_CTRL left control or right control or bothKMOD_LALT left altKMOD_RALT right altKMOD_ALT left alt or right alt or bothKMOD_LMETA left metaKMOD_RMETA right metaKMOD_META left meta or right meta or bothKMOD_CAPS caps lockKMOD_NUM num lockKMOD_MODE AltGr
(Video) Sprite Sheet Pygame Python

The modifier information is contained in the mod attribute of thepygame.KEYDOWN and pygame.KEYUP events. The mod attribute is abitmask of all the modifier keys that were in a pressed state when the eventoccurred. The modifier information can be decoded using a bitwise AND (exceptfor KMOD_NONE, which should be compared using equals ==). For example:

for event in pygame.event.get(): if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP: if event.mod == pygame.KMOD_NONE: print('No modifier keys were in a pressed state when this ' 'event occurred.') else: if event.mod & pygame.KMOD_LSHIFT: print('Left shift was in a pressed state when this event ' 'occurred.') if event.mod & pygame.KMOD_RSHIFT: print('Right shift was in a pressed state when this event ' 'occurred.') if event.mod & pygame.KMOD_SHIFT: print('Left shift or right shift or both were in a ' 'pressed state when this event occurred.')

true if the display is receiving keyboard input from the system

get_focused() -> bool

Returns True when the display window has keyboard focus from thesystem. If the display needs to ensure it does not lose keyboard focus, itcan use pygame.event.set_grab()control the sharing of input devices with other applications to grab all input.


get the state of all keyboard buttons

get_pressed() -> bools

Returns a sequence of boolean values representing the state of every key onthe keyboard. Use the key constant values to index the array. A Truevalue means that the button is pressed.


Getting the list of pushed buttons with this function is not the properway to handle text entry from the user. There is no way to know the orderof keys pressed, and rapidly pushed keys can be completely unnoticedbetween two calls to pygame.key.get_pressed(). There is also no way totranslate these pushed keys into a fully translated character value. Seethe pygame.KEYDOWN events on the pygame.eventpygame module for interacting with events and queues queue for thisfunctionality.

New in pygame 2.2.0: The collection of bools returned by get_pressed can not be iteratedover because the indexes of the internal tuple does not correpsond to thekeycodes.


determine which modifier keys are being held

get_mods() -> int

(Video) PyGame Beginner Tutorial in Python - Adding Buttons

Returns a single integer representing a bitmask of all the modifier keysbeing held. Using bitwise operators you can test if specificmodifier keys are pressed.


temporarily set which modifier keys are pressed

set_mods(int) -> None

Create a bitmask of the modifier key constantsyou want to impose on your program.


control how held keys are repeated

set_repeat() -> None

set_repeat(delay) -> None

set_repeat(delay, interval) -> None

When the keyboard repeat is enabled, keys that are held down will generatemultiple pygame.KEYDOWN events. The delay parameter is the number ofmilliseconds before the first repeated pygame.KEYDOWN event will be sent.After that, another pygame.KEYDOWN event will be sent every intervalmilliseconds. If a delay value is provided and an interval value isnot provided or is 0, then the interval will be set to the same value asdelay.

To disable key repeat call this function with no arguments or with delayset to 0.

When pygame is initialized the key repeat is disabled.


ValueError -- if delay or interval is < 0

Changed in pygame 2.0.0: A ValueError is now raised (instead of apygame.error) if delay or interval is < 0.


see how held keys are repeated

get_repeat() -> (delay, interval)

Get the delay and interval keyboard repeat values. Refer topygame.key.set_repeat()control how held keys are repeated for a description of these values.

(Video) [OUTDATED] Making a Menu - Pygame Tutorial #2

New in pygame 1.8.

get the name of a key identifier

name(key, use_compat=True) -> str

Get the descriptive name of the button from a keyboard button id constant.Returns an empty string ("") if the key is not found.

If use_compat argument is True (which is the default), this functionreturns the legacy name of a key where applicable. The return value isexpected to be the same across different pygame versions (provided thecorresponding key constant exists and is unique). If the return value ispassed to the key_code function, the original constant will be returned.

Experimental: use_compat paramater still in development for testing and feedback. It may change.Please leave use_compat feedback with authors

If this argument is False, the returned name may be prettier to displayand may cover a wider range of keys than with use_compat, but there areno guarantees that this name will be the same across different pygameversions. If the name returned is passed to the key_code function, theoriginal constant is returned back (this is an implementation detail whichmay change later, do not rely on this)

Changed in pygame 2.1.3: Added use_compat argument and guaranteed API stability for it


get the key identifier from a key name

key_code(name=string) -> int

Get the key identifier code from the descriptive name of the key. Thisreturns an integer matching one of the K_* keycodes. For example:

>>> pygame.key.key_code("return") == pygame.K_RETURNTrue>>> pygame.key.key_code("0") == pygame.K_0True>>> pygame.key.key_code("space") == pygame.K_SPACETrue

ValueError -- if the key name is not known.

New in pygame 2.0.0.


start handling Unicode text input events

(Video) Export Python pygame Game to Web with WebAssembly (pygbag tutorial)

start_text_input() -> None

Start receiving pygame.TEXTEDITING and pygame.TEXTINPUTevents. If applicable, show the on-screen keyboard or IME editor.

For many languages, key presses will automatically generate acorresponding pygame.TEXTINPUT event. Special keys likeescape or function keys, and certain key combinations will notgenerate pygame.TEXTINPUT events.

In other languages, entering a single symbol may require multiplekey presses, or a language-specific user interface. In this case,pygame.TEXTINPUT events are preferable to pygame.KEYDOWNevents for text input.

A pygame.TEXTEDITING event is received when an IME compositionis started or changed. It contains the composition text, length,and editing start position within the composition (attributestext, length, and start, respectively).When the composition is committed (or non-IME input is received),a pygame.TEXTINPUT event is generated.

Text input events handling is on by default.

New in pygame 2.0.0.


stop handling Unicode text input events

stop_text_input() -> None

Stop receiving pygame.TEXTEDITING and pygame.TEXTINPUTevents. If an on-screen keyboard or IME editor was shown withpygame.key.start_text_input(), hide it again.

Text input events handling is on by default.

To avoid triggering the IME editor or the on-screen keyboardwhen the user is holding down a key during gameplay, text inputshould be disabled once text entry is finished, or when the userclicks outside of a text box.

New in pygame 2.0.0.


controls the position of the candidate list

set_text_input_rect(Rect) -> None

This sets the rectangle used for typing with an IME.It controls where the candidate list will open, if supported.

New in pygame 2.0.0.

(Video) Pygame get_pressed and Keydown events

Edit on GitHub


1. Pygame 2 is Out! Pygame 2 & Python 3.9 Upgrade
2. Learn 2 Code E4.PYGAME All Keyed Up
(Programmer Apprentice)
3. Pygame Tutorial - 6 - Keyboard Input Controls/ Key Pressed Event
4. ChatGpt codes a game with Pygame and Python
5. Frame Rate understanding through pygame.time module (Part - 4)
(Asish Raz)
6. Pygame Key Events
(Brian Wilkinson)


Top Articles
Latest Posts
Article information

Author: Barbera Armstrong

Last Updated: 10/03/2023

Views: 5743

Rating: 4.9 / 5 (59 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Barbera Armstrong

Birthday: 1992-09-12

Address: Suite 993 99852 Daugherty Causeway, Ritchiehaven, VT 49630

Phone: +5026838435397

Job: National Engineer

Hobby: Listening to music, Board games, Photography, Ice skating, LARPing, Kite flying, Rugby

Introduction: My name is Barbera Armstrong, I am a lovely, delightful, cooperative, funny, enchanting, vivacious, tender person who loves writing and wants to share my knowledge and understanding with you.