首页 > 解决方案 > pygame.display.update() 在线程上无法正常工作

问题描述

我正在用 pygame 为我的学校项目制作游戏。我想使用另一个线程(不包括主线程)运行pygame.display.update()来更新我的游戏屏幕。

这是代码:

def display_update():
    while running: # running is declared before as True for the game loop 
        pygame.display.update()

dis  = Thread(target=display_update)
dis.start()                               

但是,代码运行后,屏幕中的图像会闪烁。

标签: python

解决方案


你不应该使用这样的线程,因为 pygame 可以很容易地在主线程中更新,并且使用带有 pygame 的线程可能会导致未定义的行为

问题是线程没有同步。如果绝对有必要使用线程,那么这样的事情应该可以工作:

running = True
do_update = False


def display_update():
    while running: # running is declared before as True for the game loop 
       if do_update:
           pygame.display.update()
           do_update = False

dis  = Thread(target=display_update)
dis.start() 

while running:
    if not do_update:
        #Code
        #Code
        #Code
    do_update = True

display_update这基本上会在更新屏幕时停止主线程。

对此进行编码的更好方法是:

while running:
    #Code
    #Code
    #Code
    pygame.display.update()

推荐阅读