Python Forum
Cannot get pygame.JOYBUTTONDOWN to register
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Cannot get pygame.JOYBUTTONDOWN to register
#1
Hello all,

I'm messing around with a usb joystick I got online, and I cannot seem to get pygame to register it. I have written the following, simple code:

import pygame as pg

pg.init()
pg.joystick.init()

screen = pg.display.set_mode((500,500))

running = True

while running:
	for event in pg.event.get():
		if event.type == pg.QUIT:
			running = False
		if event.type == pg.JOYBUTTONDOWN:
			print("button down")
		if event.type == pg.JOYBUTTONUP:
			print("button up")
			
	screen.fill((255,255,255))
	pg.display.update()
			
pg.quit()
I expected it to print when i hit a button, but it doesn't seem to be registering at all, and I don't understand why. I also copied the example code from the pygame page, and that worked. What am I missing?
Reply
#2
Try initializing the joystick individually. Assuming that it's in the zero position, this should work.
joystick_0 = pg.joystick.Joystick (0)
joystick_0 .init()
This works on my system when only one joystick is plugged in.
import pygame as pg
 
pg.init()
joystick_0 = pg.joystick.Joystick (0)
joystick_0 .init()
 
screen = pg.display.set_mode((500,500))
 
running = True
 
while running:
	for event in pg.event.get():
		if event.type == pg.QUIT:
			running = False
		if event.type == pg.JOYBUTTONDOWN:
			print("button down")
		if event.type == pg.JOYBUTTONUP:
			print("button up")
			 
	screen.fill((255,255,255))
	pg.display.update()
             
pg.quit()
Output:
pygame 2.0.1 (SDL 2.0.14, Python 3.8.10) Hello from the pygame community. https://www.pygame.org/contribute.html button down button up button down button up
Reply
#3
That works, thank you! I thought I was doing the same thing as the example in the pygame docs, but upon closer inspection, I found the following lines inside the main loop:

    # For each joystick:
    for i in range(joystick_count):
        joystick = pygame.joystick.Joystick(i)
        joystick.init()
It makes sense why mine wasn't working now, many thanks.
Reply
#4
Always happy to help Smile
Reply
#5
Thanks for trying to help!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020