在Pygame中使用线程运行无限循环



我遇到了一个问题。如果你有解决办法,请告诉我你是怎么做的。

我有几个函数,我必须使用多线程,每个函数都有一个While循环。当我使用多线程时,pygame会遇到问题。我还准备了一个示例代码,使问题更容易理解。请指导我理解这个问题。

为什么pygame冻结,程序不能正常运行?

import threading
import pygame
pygame.init()
SIZE = DW, DH = 900, 600
DS = pygame.display.set_mode(size=SIZE)
pygame.display.set_caption("Stackoverflow/Pygame/Multithreading")
FPS = 60

def main():
x = DW // 2
y = DH // 2
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
clock = pygame.time.Clock()
pygame.display.update()
DS.fill(0)
clock.tick(60)


key = pygame.key.get_pressed()

if key[pygame.K_UP]:
y -= 5
if key[pygame.K_DOWN]:
y += 5
if key[pygame.K_RIGHT]:
x += 5
if key[pygame.K_LEFT]:
x -= 5


pygame.draw.circle(surface=DS, color=(255, 100, 100), center=(x, y), radius=15)

def one():
while True:
print("One")

def two():
while True:
print("Two")

t1 = threading.Thread(target=main)
t2 = threading.Thread(target=one) 
t3 = threading.Thread(target=two)

if __name__ == '__main__':
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()

我决定解决这个问题,我会把解决方案贴出来给你。

import threading
import pygame
pygame.init()
SIZE = DW, DH = 900, 600
DS = pygame.display.set_mode(size=SIZE)
pygame.display.set_caption("Stackoverflow/Pygame/Multithreading")

def main():
x = DW // 2
y = DH // 2
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
clock = pygame.time.Clock()
pygame.display.update()
DS.fill(0)
clock.tick(60)

key = pygame.key.get_pressed()

if key[pygame.K_UP]:
y -= 5
if key[pygame.K_DOWN]:
y += 5
if key[pygame.K_RIGHT]:
x += 5
if key[pygame.K_LEFT]:
x -= 5


pygame.draw.circle(surface=DS, color=(255, 100, 100), center=(x, y), radius=15)

def one():
while True:
if not pygame.get_init():
break
pass

def two():
while True:
if not pygame.get_init():
break
pass
t2 = threading.Thread(target=one) 
t3 = threading.Thread(target=two)

t2.start()
t3.start()
main()

最新更新