pygame.key — pygame v2.6.0 documentation (2024)

pygame.key

pygame module to work with the keyboard

pygame.key.get_focused

true if the display is receiving keyboard input from the system

pygame.key.get_pressed

get the state of all keyboard buttons

pygame.key.get_mods

determine which modifier keys are being held

pygame.key.set_mods

temporarily set which modifier keys are pressed

pygame.key.set_repeat

control how held keys are repeated

pygame.key.get_repeat

see how held keys are repeated

pygame.key.name

get the name of a key identifier

pygame.key.key_code

get the key identifier from a key name

pygame.key.start_text_input

start handling Unicode text input events

pygame.key.stop_text_input

stop handling Unicode text input events

pygame.key.set_text_input_rect

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

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.')
pygame.key.get_focused()

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.

pygame.key.get_pressed()

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.

Note

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.

New in pygame 2.5.0: Iteration over the collection of bools returned by get_pressed is nowrestored. However it still does not make sense to iterate over it. Currently.

pygame.key.get_mods()

determine which modifier keys are being held

get_mods() -> int

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

pygame.key.set_mods()

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.

pygame.key.set_repeat()

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.

Raises

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.

pygame.key.get_repeat()

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.

New in pygame 1.8.

pygame.key.name()

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

pygame.key.key_code()

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
Raises

ValueError -- if the key name is not known.

New in pygame 2.0.0.

pygame.key.start_text_input()

start handling Unicode text input events

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.

pygame.key.stop_text_input()

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.

pygame.key.set_text_input_rect()

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.

Edit on GitHub

pygame.key — pygame v2.6.0 documentation (2024)

References

Top Articles
Latest Posts
Article information

Author: Rev. Leonie Wyman

Last Updated:

Views: 6558

Rating: 4.9 / 5 (79 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Rev. Leonie Wyman

Birthday: 1993-07-01

Address: Suite 763 6272 Lang Bypass, New Xochitlport, VT 72704-3308

Phone: +22014484519944

Job: Banking Officer

Hobby: Sailing, Gaming, Basketball, Calligraphy, Mycology, Astronomy, Juggling

Introduction: My name is Rev. Leonie Wyman, I am a colorful, tasty, splendid, fair, witty, gorgeous, splendid person who loves writing and wants to share my knowledge and understanding with you.