- 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.
pygame.eventpygame module for interacting with events and queues queue gets
pygame.KEYUPevents when the keyboard buttons are pressed and released. Both events have
key: an integer ID representing every key on the keyboard
mod: a bitmask of all the modifier keys that were in a pressed state when the event occurred
pygame.KEYDOWNevent has the additional attributes
unicode: a single character string that is the fully translated character entered, this takes into account the shift and composition keys
scancode: the platform-specific key code, which could be different from keyboard to keyboard, but is useful for key selection of weird keys like the multimedia keys
New in pygame 2.0.0: The
pygame.TEXTINPUTevent is preferred to the
pygame.KEYDOWN. The attribute
textcontains the input.
The following is a list of all the constants (from
pygame.localspygame constants) used to represent 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) so that your key handling code works well on both pygame 1 and pygame 2.
pygame Constant ASCII Description --------------------------------- K_BACKSPACE \b backspace K_TAB \t tab K_CLEAR clear K_RETURN \r return K_PAUSE pause K_ESCAPE ^[ escape K_SPACE space K_EXCLAIM ! exclaim K_QUOTEDBL " quotedbl K_HASH # hash 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 0 K_1 1 1 K_2 2 2 K_3 3 3 K_4 4 4 K_5 5 5 K_6 6 6 K_7 7 7 K_8 8 8 K_9 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 a a K_b b b K_c c c K_d d d K_e e e K_f f f K_g g g K_h h h K_i i i K_j j j K_k k k K_l l l K_m m m K_n n n K_o o o K_p p p K_q q q K_r r r K_s s s K_t t t K_u u u K_v v v K_w w w K_x x x K_y y y K_z z z K_DELETE delete K_KP0 keypad 0 K_KP1 keypad 1 K_KP2 keypad 2 K_KP3 keypad 3 K_KP4 keypad 4 K_KP5 keypad 5 K_KP6 keypad 6 K_KP7 keypad 7 K_KP8 keypad 8 K_KP9 keypad 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 \r 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 F1 K_F2 F2 K_F3 F3 K_F4 F4 K_F5 F5 K_F6 F6 K_F7 F7 K_F8 F8 K_F9 F9 K_F10 F10 K_F11 F11 K_F12 F12 K_F13 F13 K_F14 F14 K_F15 F15 K_NUMLOCK numlock K_CAPSLOCK capslock 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 K_AC_BACK Android back button
The keyboard also has a list of modifier states (from
pygame.localspygame constants) that can be assembled by bitwise-ORing them together.
pygame Constant Description ------------------------- KMOD_NONE no modifier keys pressed KMOD_LSHIFT left shift KMOD_RSHIFT right shift KMOD_SHIFT left shift or right shift or both KMOD_LCTRL left control KMOD_RCTRL right control KMOD_CTRL left control or right control or both KMOD_LALT left alt KMOD_RALT right alt KMOD_ALT left alt or right alt or both KMOD_LMETA left meta KMOD_RMETA right meta KMOD_META left meta or right meta or both KMOD_CAPS caps lock KMOD_NUM num lock KMOD_MODE AltGr
The modifier information is contained in the
modattribute of the
modattribute is a bitmask of all the modifier keys that were in a pressed state when the event occurred. The modifier information can be decoded using a bitwise AND (except for
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 systemget_focused() -> bool
Truewhen the display window has keyboard focus from the system. If the display needs to ensure it does not lose keyboard focus, it can use
pygame.event.set_grab()control the sharing of input devices with other applications to grab all input.
- get the state of all keyboard buttonsget_pressed() -> bools
Returns a sequence of boolean values representing the state of every key on the 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 proper way to handle text entry from the user. There is no way to know the order of keys pressed, and rapidly pushed keys can be completely unnoticed between two calls to
pygame.key.get_pressed(). There is also no way to translate these pushed keys into a fully translated character value. See the
pygame.KEYDOWNevents on the
pygame.eventpygame module for interacting with events and queues queue for this functionality.
New in pygame 2.2.0: The collection of bools returned by
get_pressedcan not be iterated over because the indexes of the internal tuple does not correpsond to the keycodes.
- determine which modifier keys are being heldget_mods() -> int
Returns a single integer representing a bitmask of all the modifier keys being held. Using bitwise operators you can test if specific modifier keys are pressed.
- temporarily set which modifier keys are pressedset_mods(int) -> None
Create a bitmask of the modifier key constants you want to impose on your program.
- control how held keys are repeatedset_repeat() -> Noneset_repeat(delay) -> Noneset_repeat(delay, interval) -> None
When the keyboard repeat is enabled, keys that are held down will generate multiple
delayparameter is the number of milliseconds before the first repeated
pygame.KEYDOWNevent will be sent. After that, another
pygame.KEYDOWNevent will be sent every
intervalmilliseconds. If a
delayvalue is provided and an
intervalvalue is not provided or is 0, then the
intervalwill be set to the same value as
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
intervalis < 0
Changed in pygame 2.0.0: A
ValueErroris now raised (instead of a
intervalis < 0.
- see how held keys are repeatedget_repeat() -> (delay, interval)
intervalkeyboard repeat values. Refer to
pygame.key.set_repeat()control how held keys are repeated for a description of these values.
New in pygame 1.8.
- get the name of a key identifiername(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.
True(which is the default), this function returns the legacy name of a key where applicable. The return value is expected to be the same across different pygame versions (provided the corresponding key constant exists and is unique). If the return value is passed to the
key_codefunction, the original constant will be returned.
use_compatparamater 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 display and may cover a wider range of keys than with
use_compat, but there are no guarantees that this name will be the same across different pygame versions. If the name returned is passed to the
key_codefunction, the original constant is returned back (this is an implementation detail which may change later, do not rely on this)
Changed in pygame 2.1.3: Added
use_compatargument and guaranteed API stability for it
- get the key identifier from a key namekey_code(name=string) -> int
Get the key identifier code from the descriptive name of the key. This returns an integer matching one of the K_* keycodes. For example:
>>> pygame.key.key_code("return") == pygame.K_RETURN True >>> pygame.key.key_code("0") == pygame.K_0 True >>> pygame.key.key_code("space") == pygame.K_SPACE True
ValueError -- if the key name is not known.
New in pygame 2.0.0.
- start handling Unicode text input eventsstart_text_input() -> None
pygame.TEXTINPUTevents. If applicable, show the on-screen keyboard or IME editor.
For many languages, key presses will automatically generate a corresponding
pygame.TEXTINPUTevent. Special keys like escape or function keys, and certain key combinations will not generate
In other languages, entering a single symbol may require multiple key presses, or a language-specific user interface. In this case,
pygame.TEXTINPUTevents are preferable to
pygame.KEYDOWNevents for text input.
pygame.TEXTEDITINGevent is received when an IME composition is started or changed. It contains the composition
length, and editing
startposition within the composition (attributes
start, respectively). When the composition is committed (or non-IME input is received), a
pygame.TEXTINPUTevent is generated.
Text input events handling is on by default.
New in pygame 2.0.0.
- stop handling Unicode text input eventsstop_text_input() -> None
pygame.TEXTINPUTevents. If an on-screen keyboard or IME editor was shown with
pygame.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 keyboard when the user is holding down a key during gameplay, text input should be disabled once text entry is finished, or when the user clicks outside of a text box.
New in pygame 2.0.0.
- controls the position of the candidate listset_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