This question already has an answer here:
Pygame using time.sleep to wait for x seconds not executing code above it
                                
                                    (1个答案)
                                
                        
                                在10个月前关闭。
            
                    
因此,我正在学习PyGame(初学者)。当我遇到在PyGame窗口上显示文本时,睡眠没有按预期进行。只要单击任何键,它就会显示该消息,然后睡眠n秒钟。但是当我尝试它时,它在显示之前已经睡了n秒钟。为什么会发生这种情况,我应该如何解决?

import pygame
import time

pygame.init()

white = (255, 255, 255)

gameDisplay = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()

def message_display(text):
    font = pygame.font.Font('freesansbold.ttf', 115)
    text_surface = font.render(text, True, (0, 0, 0))
    gameDisplay.blit(text_surface, (400, 300))
    pygame.display.update()
    time.sleep(2)

gameDisplay.fill(white)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        if event.type == pygame.KEYDOWN:
            message_display("Hello")

    pygame.display.update()

pygame.quit()

最佳答案

由于某些代码优化导致同步行为,因此在某些系统上似乎会发生这种情况。因此,在进入下一行之前强制其完成执行似乎有所帮助。 threading模块帮助实现了这一目标。

def message(text):
    font = pygame.font.Font('freesansbold.ttf', 115)
    text_surface = font.render(text, True, (0, 0, 0))
    gameDisplay.blit(text_surface, (400, 300))
    pygame.display.update()

def message_display(text):
    import threading

    p1 = threading.Thread(target=message, args=(text, ))

    # start the thread execution
    p1.start()

    # wait for it to complete to join it with the main program
    p1.join()

    time.sleep(5)

关于python - 在需要重复的地方 sleep 不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55881619/

10-12 04:03
查看更多