【问题标题】:Pygame window freezes when using threadsPygame 窗口在使用线程时冻结
【发布时间】:2019-04-28 17:09:28
【问题描述】:

我有一个 pygame 脚本,它以白屏启动,然后在用户键入内容时转换为黑屏。用户输入由另一个线程处理,我使用queue.Queue 将消息从输入线程传递到 pygame 线程。

问题是每当我运行脚本时,pygame 窗口都会在片刻后冻结。如果我快速输入内容,屏幕将从白色变为黑色,但窗口仍然冻结。我不确定脚本卡在哪里?

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

【问题讨论】:

    标签: python pygame python-multithreading


    【解决方案1】:

    好的,我刚刚发现在线程中运行 pygame 位会导致窗口冻结。如果我只为inputFunc 创建一个线程并调用screen_1 一切正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-26
      • 1970-01-01
      • 1970-01-01
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多