我有一个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()
答案 0 :(得分:1)
好吧,我刚刚发现在线程中运行pygame位会导致窗口冻结。如果我仅为inputFunc
创建一个线程并调用screen_1
,那么一切都很好。