Here’s my Code and I am just trying run my xbox controller for later on if statements to control dc motors:
pygame.init() joystick = [] clock = pygame.time.Clock() for i in range(0, pygame.joystick.get_count()): joystick.append(pygame.joystick.Joystick(i)) joystick[-1].init() while True: clock.tick(60) for event in pygame.event.get(): if event.button == 0: print ("A Has Been Pressed") elif event.button == 1: print ("B Has Been Pressed") elif event.button == 2: print ("X Has Been Pressed") elif event.button == 3: print ("Y Has Been Pressed")
I get the error message below when I run my code:
pygame 1.9.4.post1 Hello from the pygame community. https://www.pygame.org/contribute.html A Has Been Pressed Traceback (most recent call last): File "/home/pi/Documents/Code/Practice.py", line 13, in <module> if event.button == 0: AttributeError: 'Event' object has no attribute 'button'
Advertisement
Answer
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 MOUSEMOTION
or MOUSEBUTTONDOWN
. However all event objects have a type
attribute. Check the event type
attribute before the button
attribute (see pygame.event
):
while True: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 0: print ("A Has Been Pressed") elif event.button == 1: print ("B Has Been Pressed") elif event.button == 2: print ("X Has Been Pressed") elif event.button == 3: print ("Y Has Been Pressed")
The MOUSEBUTTONDOWN
event occurs once when you click the mouse button and the MOUSEBUTTONUP
event occurs once when the mouse button is released. The pygame.event.Event()
object has two attributes that provide information about the mouse event. pos
is a tuple that stores the position that was clicked. button
stores the button that was clicked. Each mouse button is associated a value. For instance the value of the attributes is 1, 2, 3, 4, 5 for the left mouse button, middle mouse button, right mouse button, mouse wheel up respectively mouse wheel down. When multiple keys are pressed, multiple mouse button events occur.