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

独立函数定义的score_turtle引发Turtle游戏NameError问题求助

修复Turtle游戏中的NameError问题

问题原因

score_turtle是score_turtle_setup函数内部定义的局部变量,函数执行完毕后该变量仅存在于函数的局部作用域中,全局作用域和handle_click函数无法访问到它,因此点击海龟时会抛出NameError: name 'score_turtle' is not defined错误。

修复方案

将score_turtle声明为全局变量,让handle_click函数可以正常访问它。具体修改如下:

  • 在全局作用域中声明score_turtle变量
  • 在score_turtle_setup函数中使用global关键字标记该变量为全局变量

修改后的完整代码

import turtle
import random

screen = turtle.Screen()
screen.bgcolor("light blue")
FONT = ('Arial', 25, 'normal')
skor = 0
turtle_list = []
score_turtle = None  # 全局声明score_turtle


# score turtle
def score_turtle_setup():
    global score_turtle  # 标记为全局变量
    score_turtle = turtle.Turtle()
    score_turtle.hideturtle()
    score_turtle.penup()
    score_turtle.color("dark blue")
    top_screen = screen.window_height() / 2
    y = top_screen * 0.85
    score_turtle.setpos(-200, y)
    score_turtle.write(arg=f"SCORE: 0", move=False, align="center", font=FONT)


def make_turtle(x, y):
    point = turtle.Turtle()

    def handle_click(x, y):
        global skor
        skor += 1
        # 先清除之前的分数文本,避免重叠
        score_turtle.clear()
        score_turtle.write(arg=f"SCORE: {skor}", move=False, align="center", font=FONT)

    point.onclick(handle_click)
    point.shape("turtle")
    point.penup()
    point.color("green")
    point.shapesize(1.5)
    point.goto(x * 12, y * 12)
    turtle_list.append(point)


x_coordinats = [-20, -10, 0, 10, 20]
y_coordinats = [20, 10, 0, -10]


def setup_turtles():
    for x in x_coordinats:
        for y in y_coordinats:
            make_turtle(x, y)


def hide_turtles():
    for point in turtle_list:
        point.hideturtle()


def show_turtles():
    random.choice(turtle_list).showturtle()


turtle.tracer(0)

score_turtle_setup()
setup_turtles()
hide_turtles()
show_turtles()

turtle.tracer(1)

turtle.mainloop()

额外优化:在handle_click中加入score_turtle.clear(),避免每次更新分数时文本重叠在一起。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 15:10:35