I am trying to create a Thread that will continuously run in the background of my program and check whether or not the user has pressed the X button in the top right of the window, and then quit the program if they do press it. This way, no matter what is happening, the user may close the program at any point.
I am new to how Threads work so please bear with me. Here's a simplified version of my code that doesn't work:
from threading import Thread import pygame, sys def checkForQuit(): while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() pygame.time.wait(100) # 100ms if __name__ == "__main__": screen = pygame.display.set_mode((300, 300)) quitThread = Thread(target = checkForQuit) quitThread.start()
The problem with my code right now is that when I run it, the program cannot tell whether or not the close button was pressed or not, and the window hangs until it crashes. I'm not sure if there is an easier way to accomplish my task.
I've tried searching for a question similar but I also don't really know what I'm looking for. Any help is appreciated :)