2

Hi there I'm trying to detect if the "w" key is pressed and I keep getting an error and can't see where I've went wrong. Grateful for advice.

  while 1: 
    for event in pygame.event.get():
      if event.type == pygame.QUIT: 
        sys.exit()
      if event.key == pygame.K_w:    #line 82
        player.walkNorthAnimation()
        t.displayTree()

The error is:

Traceback (most recent call last):
  File "unnamed.py", line 91, in <module>
    main()
  File "unnamed.py", line 82, in main
    if event.key == pygame.K_w:
AttributeError: event member not defined
1
  • Probably, you are catching an event of invalid type. Could you log event inside for loop and post the output here? Commented Jan 3, 2016 at 10:06

1 Answer 1

1

You have to check event.type == pygame.KEYDOWN or event.type == pygame.KEYUP before you use event.key because not all events have event.key defined.

while True: 
    for event in pygame.event.get():
        if event.type == pygame.QUIT: 
            sys.exit()
        elif event.type == pygame.KEYDOWN: 
            if event.key == pygame.K_w:    #line 82
                player.walkNorthAnimation()

see PyGame documentation: Event

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.