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

Python实现文本显示3秒后消失的方法(初学者小游戏需求)

实现文本3秒后自动消失的基础代码(Pygame示例)

下面是适合小游戏初学者的Python Pygame实现方案:

1. 先安装Pygame

在终端执行安装命令:

pip install pygame

2. 完整实现代码

import pygame
import sys

# 初始化Pygame
pygame.init()

# 创建游戏窗口
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption("文本自动消失演示")

# 配置文本样式
font = pygame.font.Font(None, 48)
text_surface = font.render("3秒后自动消失", True, (255, 255, 255))
text_rect = text_surface.get_rect(center=(200, 150))

# 记录文本开始显示的时间戳
start_time = pygame.time.get_ticks()
show_text = True

# 游戏主循环
running = True
while running:
    current_time = pygame.time.get_ticks()
    
    # 判断是否已过3秒(3000毫秒)
    if current_time - start_time >= 3000:
        show_text = False
    
    # 处理窗口关闭事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    
    # 填充背景色
    screen.fill((0, 0, 0))
    
    # 根据状态决定是否绘制文本
    if show_text:
        screen.blit(text_surface, text_rect)
    
    # 更新屏幕显示
    pygame.display.flip()

# 退出游戏
pygame.quit()
sys.exit()

核心逻辑说明

  • pygame.time.get_ticks():获取从Pygame初始化到当前的毫秒数,用来计算时间差
  • show_text布尔变量:控制文本的显示状态,时间差超过3秒后切换为False
  • 主循环中持续检查时间状态,动态更新文本显示

如果用其他语言/框架(比如HTML5、Unity),可以说明需求,我会给出对应实现示例。

内容的提问来源于stack exchange,提问作者lggergo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 17:17:00