PyGame window stopped showing up

Viewed 517

I've been learning python and decided to play around with PyGame. The PyGame window randomly stops showing up when I run the script. I don't get any errors or anything, the PyGame window just won't appear.

The scripts used to work, now they don't. I had this issue before and restarted my computer a few times and eventually it started working again. But it's happening again.

So, I've got no clue what's causing it and no clue how to fix it. I've tried it with two different PyGame scripts, neither work. I'll post a sample script below.

Im using:

  • PyGame v2.0.1
  • SDL v2.0.14
  • Python 3.7.3
  • OS: Windows 10
  • IDE: PyCharm

I know PyGame version 2 is new, is this a bug with the new version? Thanks for your help.

Edit: restarting the computer once again fixed the issue in the short-term. I'm still looking for a long-term solution to the problem so I don't have to the restart the computer every time this happens.

Here's some sample code:

import pygame, sys
pygame.init()
windowSize = sizeW, sizeH = 1920, 1080
window = pygame.display.set_mode(windowSize)
pygame.display.set_caption('Test')
black = 0, 0, 0
speed = 0.2
x, y = 50, 50
h, w = 50, 50
blue = 0, 0, 255

guy = pygame.image.load('tile032.png')

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT] and x - speed > 0:
        x -= speed
    if keys[pygame.K_RIGHT] and x + w + speed < sizeW:
        x += speed
    if keys[pygame.K_UP] and y - speed > 0:
        y -= speed
    if keys[pygame.K_DOWN] and y + speed + h < sizeH:
        y += speed

    window.fill(black)
    window.blit(guy, (x,y))
    pygame.display.update()
4 Answers

Handle the closing window properly , use pygame.quit().

for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

This issue usually comes when you are exiting pygame window just after calling it. It can be resolved by exiting the pygame only after the run variable goes as False. Either make the logic when your program ends or after the run function is defined as false.

After the Pygame window closes, look at the terminal to see if there is an error. If you don't use Linux, look at the place where the error usually comes up.

How I usually do it is have pygame.quit() at the very end of the code, outside of every loop, class, and method. I don't usually use sys.exit() since I am a very new pygame user, but you should also set run to false in the event loop so then it hits that pygame.quit() method at the end. And like others suggest, maybe have sys.exit() after that too.

Related