unibookworm
unibookworm

Reputation: 11

Pygame window freezes when using threads

I have a pygame script that starts up with a white screen and then transitions to a black screen when the user types something. The user input is handled by another thread and I used queue.Queue to pass messages from the input thread to the pygame one.

The problem is that whenever I run the script the pygame window will freeze after a short while. If I type in something quickly the screen will change from white to black but the window still freezes. I'm not sure where the script gets stuck?

import pygame
import threading 
import queue

q = queue.Queue()

pygame.init()

#rgb codes 
black = (0, 0, 0)
white = (255, 255, 255)

game_display = pygame.display.set_mode((800, 800))

def screen_1():

    crashed = False

    #holds messages from input thread
    msg = ''

    game_display.fill(white)

    while not crashed:

        #check if there are any messages in the queue
        try:
            msg = q.get(False)
        except queue.Empty:
            pass

        if msg:
            return screen_2()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                crashed = True        

        pygame.display.update()

def screen_2():

    crashed = False

    game_display.fill(black)

    while not crashed:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                crashed = True

        pygame.display.update()        

def inputFunc():
    msg = input('Type something:\n')
    q.put(msg)

t1 = threading.Thread(target = screen_1)
t2 = threading.Thread(target = inputFunc)

t1.start()
t2.start()

Upvotes: 0

Views: 512

Answers (1)

unibookworm
unibookworm

Reputation: 11

Ok I just figured out that running the pygame bit in a thread causes the window to freeze. If I only create a thread for inputFunc and call screen_1 everything works just fine.

Upvotes: 1

Related Questions