1

Hi there is an issue that doesn't really matter when developing a game with pygame but that kept on bothering me for a while.

    while not gameExit:
        for event in pygame.event.get():e
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    pass

so above is a working code and I believe

    while not gameExit:
        for event in pygame.event.get():e
            if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
                pass

works as well.

However, when I just try something like "event.key == pygame.K_RIGHT:", python gives me an error saying there is no attribute 'key'. While I know it'd be more reasonable to choose above 2 codes over just "event.key == pygame.K_RIGHT:", I don't know why pygame would say the event doesn't have the attribute 'key' while when I simply check if event.type == pygame.KEYDOWN pygame will have no problem executing "event.key == pygame.K_RIGHT".

Could it be that checking if event.type == pygame.KEYDOWN actually generates a 'key' attribute for the event?

1 Answer 1

2

Not every event has all possbile attributes. that's why you have to check the type of the event first.

Here's a list of all attributes for each event type:

QUIT             none
ACTIVEEVENT      gain, state
KEYDOWN          unicode, key, mod
KEYUP            key, mod
MOUSEMOTION      pos, rel, buttons
MOUSEBUTTONUP    pos, button
MOUSEBUTTONDOWN  pos, button
JOYAXISMOTION    joy, axis, value
JOYBALLMOTION    joy, ball, rel
JOYHATMOTION     joy, hat, value
JOYBUTTONUP      joy, button
JOYBUTTONDOWN    joy, button
VIDEORESIZE      size, w, h
VIDEOEXPOSE      none
USEREVENT        code

As you can see, only KEYDOWN and KEYUP events have the key attribute.

Sign up to request clarification or add additional context in comments.

2 Comments

yeah but if I press a key, wouldn't it be a keydown event whether or not I ask python if it is a keydown event?(and shouldn't it have the KEY attribute thus?)
Yes, if you press a key, you get a KEYDOWN event. But if you iterate over all events returned from pygame.event.get(), you will get also events other than KEYDOWN (like e.g. MOUSEMOTION) which in turn does not have a KEY attribute. Of course you could also call pygame.event.get(pygame.KEYDOWN) to only get KEYDOWN events, so don't have to check for the type (but you still would have to call pygame.event.get() after that so the event queue doesn't get full).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.