在单独的函数中定义变量后出现 Turtle NameError

问题描述 投票:0回答:1

我想创建一个乌龟游戏。当我点击游戏中的乌龟形状时,它应该给出+1分,以便我可以计算分数。但是,当我执行命令并单击海龟形状时,它给我一个名称错误,即

NameError: name 'score_turtle' is not defined
,即使它是在上面的命令中定义的。请帮我解决它。

import turtle
import random

screen = turtle.Screen()
screen.bgcolor("light blue")
FONT = ('Arial', 25, 'normal')
skor = 0
turtle_list = []


#score turtle


def score_turtle_setup():
    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.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()

我尝试从

score_turtle_setup
函数调用函数
handle_click
,但没有成功。

python turtle-graphics python-turtle
1个回答
1
投票

默认情况下,变量的作用域为函数。这意味着当函数返回时,函数作用域中的所有变量都将被销毁。幸运的是,函数允许您返回值,因此您可以执行以下操作:

def score_turtle_setup():
    score_turtle = turtle.Turtle()
    # ...
    return score_turtle

# ...
score_turtle = score_turtle_setup()

现在

score_turtle
变量已在全局范围内分配,可以从任何其他函数访问它。

这可能不是一个很好的设计,但是对于一个小程序来说,还可以。接下来,如果程序增长,请考虑使用类和/或模块来封装这样的逻辑实体。

© www.soinside.com 2019 - 2024. All rights reserved.