Pitu
Pitu

Reputation: 97

Pygame, screen only updates when exiting pygame window?

I'm fairly new to pygame and i needed some help because my code is not working properly.

Okay so here's the problem: I want the screen to turn white when i run it but it remains black, however when i press the exit, it turns white for about a second and then closes.

This also happens when i put a picture (like the player.png) it appears for about a second before exiting. I don't know what i'm doing wrong,

please help fix the code and explain why it is happening?

here is the code:

import pygame

pygame.init()

screen = pygame.display.set_mode((640,480))
image = pygame.image.load('player.png')
gameExit = False
gameLoop = True

pygame.display.update()
white = (255,255,255)

while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
        gameExit = True

    for event in pygame.event.get():
        screen.fill(white)







pygame.display.update()




pygame.quit()
quit()

PS. I don't get any errors

Upvotes: 2

Views: 1122

Answers (2)

Henry
Henry

Reputation: 88

Ok, so I agree with Sloth, but instead of doing all the screen updating and filling and blitting at the end, making the script less readable, you should make like an animate function that runs at the end of the while loop each time, and put the blitting and screen updating stuff in that function. Sorry for the run-on sentence.

Oh and you don't need your GameLoop variable.

Upvotes: 0

sloth
sloth

Reputation: 101042

Python is indentation sensitive. In your code, you call pygame.display.update() only once your main loop ends.

Also, you only paint the background white in the case there's an event in the event queue between the two for loops, and then you fill the background for every event in the queue.

Note that this could also lead to a situation in which your QUIT event is "swallowed" by the second loop.


So this

while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
        gameExit = True

    for event in pygame.event.get():
        screen.fill(white)

pygame.display.update()

should be

while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True

    screen.fill(white)

    pygame.display.update()

Upvotes: 1

Related Questions