首页 > 解决方案 > 按钮不在事件内?

问题描述

我正在为我的 xbox one 控件使用 pygame,应该有一些名为按钮的东西,但它会抛出一个错误说AttributeError: 'Event' object has no attribute 'button'

这是整个代码

import pygame
pygame.init()
joysticks = []
clock = pygame.time.Clock()
keepPlaying = True

# for al the connected joysticks
for i in range(0, pygame.joystick.get_count()):
    # create an Joystick object in our list
    joysticks.append(pygame.joystick.Joystick(i))
    # initialize them all (-1 means loop forever)
    joysticks[-1].init()
    # print a statement telling what the name of the controller is
    print ("Detected joystick "),joysticks[-1].get_name(),"'"
while keepPlaying:
    for event in pygame.event.get():
        print(event)
        if event.button == 0:
            print ("A Has Been Pressed")

当我按下它时,它会打印<Event(1539-JoyButtonDown {'joy': 0, 'instance_id': 0, 'button': 0})>出一个按钮,但它会抛出错误

标签: pythonpygame

解决方案


每种事件类型都会生成一个pygame.event.Event具有不同属性的对象。button没有为所有事件对象定义该属性。您可以button从鼠标或操纵杆事件(如JOYBUTTONUPor )中获取属性JOYBUTTONDOWN。然而,所有事件对象都有一个type属性。type在属性之前检查事件属性button(请参阅pygame.event):

while keepPlaying:
    for event in pygame.event.get():
        print(event)
        if event.type == JOYBUTTONDOWN:
            if event.button == 0:
                print ("A Has Been Pressed")

推荐阅读