button not inside event?

Viewed 89

I'm using pygame for my xbox one control and there should be something named button but it throws an error saying AttributeError: 'Event' object has no attribute 'button'

this is the entire code

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

when i press a it prints <Event(1539-JoyButtonDown {'joy': 0, 'instance_id': 0, 'button': 0})> there should be a button attrabute but it throws the error instead

1 Answers

Each event type generates a pygame.event.Event object with different attributes. The button attribute is not defined for all event objects. You can just get the button attribute from a mouse or joystick event like JOYBUTTONUP or JOYBUTTONDOWN. However all event objects have a type attribute. Check the event type attribute before the button attribute (see 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")
Related