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

Pygame进度条开发报错:'pygame.Surface'对象不可下标访问

问题修正方案

错误原因

你在循环里执行了text = font.render(text[textIndex], False, (0, 255, 0)),这行代码把原本存储状态字符串列表的text变量,覆盖成了font.render()返回的Pygame Surface对象。后续代码里的text[textIndex]试图对Surface对象做下标访问,而Surface不支持这种操作,因此抛出TypeError。

修正步骤

  1. 给渲染后的Surface对象换个独立变量名,避免覆盖原字符串列表
  2. 添加清屏逻辑,防止每次渲染的文字重叠显示
  3. 补充进度条的绘制逻辑(匹配你原本的功能需求)

修正后的完整代码

import pygame
pygame.init()
window = pygame.display.set_mode((pygame.display.Info().current_w, pygame.display.Info().current_h))
# 保留原字符串列表,用新变量名避免冲突
status_texts = ["Reading data ...", "Setting configs ...", "Loading files ...", "Download complete"]
textIndex = 0
font = pygame.font.SysFont("Arial", 30)

y2 = 400
# 进度条基础参数
bar_width = 600
bar_height = 40
bar_x = (pygame.display.Info().current_w - bar_width) // 2
bar_y = y2 + 60
progress = 0
# 每个状态对应25%进度,控制增长速度
progress_step = 0.25 / 100

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
    
    # 清屏,避免文字和进度条重叠
    window.fill((0, 0, 0))
    
    # 渲染当前状态文本,用新变量存储Surface
    rendered_text = font.render(status_texts[textIndex], False, (0, 255, 0))
    # 自动计算居中坐标,比手动计算更准确
    text_rect = rendered_text.get_rect(center=(pygame.display.Info().current_w//2, y2))
    window.blit(rendered_text, text_rect)
    
    # 绘制进度条背景
    pygame.draw.rect(window, (50, 50, 50), (bar_x, bar_y, bar_width, bar_height), border_radius=5)
    # 绘制当前进度
    current_progress_width = int(bar_width * progress)
    pygame.draw.rect(window, (0, 255, 0), (bar_x, bar_y, current_progress_width, bar_height), border_radius=5)
    
    pygame.display.flip()
    
    # 模拟进度推进(可替换为实际任务逻辑)
    if progress < 1.0:
        progress += progress_step
    else:
        if textIndex < len(status_texts) - 1:
            textIndex += 1
            progress = 0
        else:
            # 所有状态完成后可停止或循环
            pass

额外说明

  • 用status_texts存储原字符串列表,彻底避免了变量覆盖问题
  • 使用get_rect()实现文本居中,比固定字符宽度计算更精准
  • 补充了完整的进度条绘制逻辑,你可以根据需求调整样式和进度更新规则
  • 修复了退出逻辑,改用pygame.quit()+exit(),符合Pygame规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 00:50:36