r/PythonLearning • • 3d ago

Help Request Problem with pygame not responding

Hello, I am relatively new to python and am trying to learn pygame. I am attempting to make a game where you have to guess the song and I'm playing the mp3 with the pygame mixer. Before I added the song, it just opened a window with colored background and some text. When I put in the music it plays normally, I can pause it and resume it via terminal, however the window that was opening before now shows black and isn't responding. I have no idea what is causing this and can't find anything on the internet. Does anyone know whats happening?

Here is the code:

#load and initialize
import pygame
pygame.init()
pygame.mixer.init()


#window info
displayw = 640
displayh = 550
screen = pygame.display.set_mode((displayw,displayh))
title = pygame.display.set_caption("game")


#clock
clock = pygame.time.Clock()


file = "song.mp3"
pygame.mixer.music.load(file)
pygame.mixer.music.set_volume(0.7)
pygame.mixer.music.play()



class MainRun(object):
    def __init__(self,displayw,displayh):
        self.dw = displayw
        self.dh = displayh
        self.Main()


    def Main(self):
        running = True
        font = pygame.font.Font(None, size = 45)
        text = font.render("text", True, (200,200,200))


        while running:
            screen.fill((60,21,70))


            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()
                elif event.type == pygame.KEYDOWN:
                    running = False


            print("Press 'p' to pause, 'r' to resume")
            print("Press 'e' to exit the program")
            userinput = input("  ")
            
            if userinput == 'p':
                pygame.mixer.music.pause()     
            elif userinput == 'r':
                pygame.mixer.music.unpause()
            elif userinput == 'e':
                pygame.mixer.music.stop()
                break


            screen.blit(text, (195,100))


            pygame.display.flip()
            clock.tick(60)


if __name__ == '__main__':
    MainRun(displayw,displayh)
2 Upvotes

2 comments sorted by

1

u/Sea-Ad7805 3d ago edited 3d ago

userinput = input(" ") is blocking, so the window is't drawn anymore. Don't use input() in the while running main loop. Instead use events to test which keys are pressed, see: https://www.geeksforgeeks.org/python/pygame-input-handling/

2

u/ShadowFoxy122 2d ago

Oh I see, I didn't know thats how it works, it's running correctly now thank you!