【问题标题】:Attribute error : member not defined python属性错误:成员未定义python
【发布时间】:2016-04-07 03:05:05
【问题描述】:

您好,我正在尝试检测是否按下了“w”键,但我不断收到错误消息,看不到哪里出错了。感谢您的建议。

  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()

错误是:

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

【问题讨论】:

  • 很可能,您正在捕获无效类型的事件。您可以在for 循环中记录event 并在此处发布输出吗?

标签: python pygame attributeerror


【解决方案1】:

在使用event.key 之前,您必须检查event.type == pygame.KEYDOWNevent.type == pygame.KEYUP,因为并非所有事件都定义了event.key

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()

请参阅 PyGame 文档: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

【讨论】:

    猜你喜欢
    • 2021-09-01
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多