(Python) Closing pygame.display in a Thread

Refresh

1 weeks ago

Views

18 time

2

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

1 answers

0

Обычно вы закрываете Pygame этого пути. Там не должно быть нить, необходимое для этого.

import pygame, sys

def main():
    pygame.init()
    screen = pygame.display.set_mode((300, 300))
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

if __name__ == "__main__":
    main()

Если вы хотите, чтобы закрыть его с резьбой, вы можете попробовать это так.

import threading
import pygame
import sys

def main():
    pygame.init()
    screen = pygame.display.set_mode((300, 300))
    global running
    running = True

    def programCheck():
        while True:
            if not running:
                sys.exit(0)
        pygame.time.wait(100)
    t = threading.Thread(target=programCheck)
    t.start()

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                running = False

if __name__ == "__main__":
    main()