You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Pygame开发时如何实现延迟1秒切换屏幕显示的文本内容?

问题原因

  • 你在键盘事件逻辑中直接使用了time.sleep(1.5),这个操作会阻塞Pygame的整个主循环,阻塞期间屏幕渲染、刷新的逻辑完全不会执行。因此你修改displaytext = text1之后的1.5秒里,程序卡住没有做任何画面更新,等sleep结束直接把displaytext改成了text2,自然看不到text1的展示效果。
  • Pygame的运行机制要求主循环必须持续运行,任何阻塞操作都会导致窗口无响应、画面不更新的问题。

修正方案

不要用time.sleep做延迟,改用Pygame的时间戳来判断切换时机,修改后的可用代码如下:

import pygame, sys
from pygame.locals import *

pygame.init()

text1 = "text 1"
text2 = "text 2"
displaytext = ""
# 新增状态变量:是否触发了切换、切换的时间节点
switch_triggered = False
switch_time = 0

screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("text test")
# 时钟对象用来控制帧率,降低CPU占用
clock = pygame.time.Clock()

font = pygame.font.SysFont("None", 24)
text = font.render(str(displaytext), True, (255,255,255))
textRect = text.get_rect()
textRect.center = (300, 250)

while True:
    # 获取当前程序运行时间(单位:毫秒)
    current_time = pygame.time.get_ticks()
    screen.fill((0,0,0))
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            if event.key == K_SPACE and not switch_triggered:
                displaytext = text1
                switch_triggered = True
                # 记录1.5秒后的切换时间点
                switch_time = current_time + 1500
    
    # 到达时间点后切换文本
    if switch_triggered and current_time >= switch_time:
        displaytext = text2
        switch_triggered = False # 重置状态,后续按空格可再次触发
    
    text = font.render(str(displaytext), True, (255,255,255))
    
    screen.blit(text, textRect)
    pygame.display.update()
    clock.tick(60) # 固定60帧运行

内容的提问来源于stack exchange,提问作者Chadwickus Broski-Hamstick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 07:12:04