Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you exit only a pygame window and not the whole code?

My program doesn’t only use Pygame, but also Tkinter, so I have a tkinter window running while the pygame window is. It is common practice that in Pygame code you do sys.exit() to stop the pygame.error: video system not initialized error, take the code snippet below for example. The problem with this is that if you aren’t only running pygame code, this "solution" would be stopping everything in the code instead of just the pygame window. (FYI, this error does not make the program crash or stop, so it’s only a console thing, but it’s still annoying anyways).

import pygame, sys
  
while True:  # event loop
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
        pygame.display.update()

So, are there any alternatives to sys.exit() that only exit the pygame code?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

sys.exit() terminates the interpreter. pygame.quit uninitialize all pygame modules. Once you have called pygame.quit(), calling any other pygame statement will cause an exception. Call pygame.quit() after the application loop and remove sys.exit():

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    # [...]
    pygame.display.update()

pygame.quit()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading