Attribute error : member not defined python

大兔子大兔子 提交于 2019-12-11 01:24:29

问题


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:


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



回答2:


Use dir(event) to show the attributes of the event to see if the event.key really exists.



来源:https://stackoverflow.com/questions/34575274/attribute-error-member-not-defined-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!