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

Pygame Zero报NameError: screen未定义错误问题咨询

报错根因

Pygame Zero的内置全局对象screen,仅在框架完成初始化、进入内置生命周期回调阶段后才会生效。你将screen.draw.textbox()相关调用写在了全局顶层作用域,这部分代码会在pgzrun.go()启动框架前执行,此时screen对象还未被创建,因此触发NameError: name 'screen' is not defined错误。

Pygame Zero的固定规则是:所有绘制相关逻辑,必须放在框架内置的draw()函数内,框架会在初始化完成后自动调用draw(),此时可正常访问screen对象。

修复方法
  • 删除全局作用域下(即question = questions.pop(0)之后)所有调用screen.draw的代码
  • 将上述文本绘制逻辑,移动到draw()函数内部,放在色块绘制代码之后(避免色块覆盖文字)
修正后的draw函数代码
def draw():
    screen.fill("dim grey")
    screen.draw.filled_rect(main_box, "sky blue")
    screen.draw.filled_rect(timer_box, "sky blue")

    for box in answer_boxes:
        screen.draw.filled_rect(box, "orange")
    
    # 绘制题目、选项、计时器文本
    screen.draw.textbox(str(time_left), timer_box, color=("black"))
    screen.draw.textbox(question[0], main_box, color=("black"))

    index = 1
    for box in answer_boxes:
        screen.draw.textbox(question[index], box, color=("black"))
        index += 1

修改后重新运行即可消除该报错,正常显示游戏界面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 04:30:51