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
andpygame.KEYUP
events when the keyboard buttons are pressed and released. Both events havekey
andmod
attributes.key
: an integer ID representing every keyon the keyboardmod
: a bitmask of all the modifier keysthat were in a pressed state when the event occurred
The
pygame.KEYDOWN
event has the additional attributesunicode
andscancode
.unicode
: a single character string that is the fully translatedcharacter entered, this takes into account the shift and composition keysscancode
: 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 theunicode
attributeofpygame.KEYDOWN
. The attributetext
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 PythonThe modifier information is contained in the
mod
attribute of thepygame.KEYDOWN
andpygame.KEYUP
events. Themod
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 (exceptforKMOD_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()¶
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.
- 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
True
value 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. Seethepygame.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.
- pygame.key.get_mods()¶
determine which modifier keys are being held
get_mods() -> int
(Video) PyGame Beginner Tutorial in Python - Adding ButtonsReturns 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. Thedelay
parameter is the number ofmilliseconds before the first repeatedpygame.KEYDOWN
event will be sent.After that, anotherpygame.KEYDOWN
event will be sent everyinterval
milliseconds. If adelay
value is provided and aninterval
value isnot provided or is 0, then theinterval
will be set to the same value asdelay
.To disable key repeat call this function with no arguments or with
delay
set to 0.When pygame is initialized the key repeat is disabled.
- Raises
ValueError -- if
delay
orinterval
is < 0
Changed in pygame 2.0.0: A
ValueError
is now raised (instead of apygame.error
) ifdelay
orinterval
is < 0.
- pygame.key.get_repeat()¶
see how held keys are repeated
get_repeat() -> (delay, interval)
Get the
delay
andinterval
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 #2New 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 isTrue
(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 thekey_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 authorsIf this argument is
False
, the returned name may be prettier to displayand may cover a wider range of keys than withuse_compat
, but there areno guarantees that this name will be the same across different pygameversions. If the name returned is passed to thekey_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
(Video) Export Python pygame Game to Web with WebAssembly (pygbag tutorial)start_text_input() -> None
Start receiving
pygame.TEXTEDITING
andpygame.TEXTINPUT
events. 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 notgeneratepygame.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 topygame.KEYDOWN
events for text input.A
pygame.TEXTEDITING
event is received when an IME compositionis started or changed. It contains the compositiontext
,length
,and editingstart
position within the composition (attributestext
,length
, andstart
, respectively).When the composition is committed (or non-IME input is received),apygame.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
andpygame.TEXTINPUT
events. 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.
(Video) Pygame get_pressed and Keydown events
pygame.key — pygame v2.4.0 documentation (2023)
Videos
1. Pygame 2 is Out! Pygame 2 & Python 3.9 Upgrade
(DevHedron)
2. Learn 2 Code E4.PYGAME All Keyed Up
(Programmer Apprentice)
3. Pygame Tutorial - 6 - Keyboard Input Controls/ Key Pressed Event
(buildwithpython)
4. ChatGpt codes a game with Pygame and Python
(echohive)
5. Frame Rate understanding through pygame.time module (Part - 4)
(Asish Raz)
6. Pygame Key Events
(Brian Wilkinson)
References
Top Articles
Cybercriminalité : faites attention à ce que vous dites à votre assistant chatbot…
3 perspectives de plaquage défensif à mi-parcours pour les Chiefs à cibler
Comment apprendre une langue RAPIDEMENT ! (Mon plan étape par étape sur 3 mois) - Luca Lampariello
Maillot Lakers Austin 316
17: “What Shall I Do to Inherit Eternal Life?” (Matthew 18; Luke 10)
Classify Each Item By The Class Of Molecule To Which It Relates.
What Is The Maximum Number Of Electrons That Can Occupy The Anti-Bonding Molecular Orbitals In A Diatomic Molecule?
Latest Posts
Every Good Girl Needs A Little Thug Lyrics
Jump Up Rollie Rollie Jump Back Rollie Rollie Lyrics
I Like To Move It
Jump Into The Fire
Which Birds Big Does The Bill Of A Platypus Resemble Resulting In A Common Name It Is Known By
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.