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?

>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()

Leave a Reply