Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

python - Getting Pygame keyboard input and check if it's a number

I am trying to get keyboard input using Pygame using this command:

if event.type == pg.KEYDOWN:
    # ADD KEYBOARD EVENTS
    keys = pg.key.get_pressed()

I want to check if the button pressed represents a number, I already know how to check if a string represent a number using try/except command, but, in my code keys is not a string, it is a huge tuple - and I don't know how to get it in an efficient way because every time I look in the internet on how to get keyboard input, they need to equate keys to something like pygame.pygame.K_LEFT and I don't want to do this for each number and furthermore every number in the number-pad (right side).

Is there an efficient way to determine if a user clicked on a number? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

pygame.key.get_pressed() returns a list with the state of all keyboard buttons. This is not intended to get the key of a keyboard event. The key that was pressed can be obtained from the key attribute of the pygame.event.Event object:

if event.type == pg.KEYDOWN:
    if event.key == pg.K_a:
        # [...] 

unicode contains a single character string that is the fully translated character:

if event.type == pg.KEYDOWN:
    if event.unicode == 'a':
        # [...] 

See also pygame.key.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...