python 使用turtle时出现错误“turtle.Terminator”

f87krz0w  于 2023-05-16  发布在  Python
关注(0)|答案(1)|浏览(579)

我创建了一个使用Python中turtle模块的函数:

def printmaze(sizeX, sizeY, walls):

    startX = -300
    startY = 300

    high = (-startX // sizeX) * 2
    width = (startY // sizeY) * 2

    turtle.clear()
    turtle.speed(0)
    turtle.penup()
    turtle.goto(-startX, startY)
    turtle.pendown()
    turtle.goto(-startX, -startY)
    turtle.goto(startX, -startY)

    turtle.setheading(0)
    for i in range(sizeX):
        turtle.penup()
        turtle.goto(startX, startY - high * i)
        for l in range(sizeY):
            if walls[i][l][1] ==  1:
                turtle.pendown()
            else:
                turtle.penup()
            turtle.forward(width)

    turtle.right(90)
    for i in range(sizeY):

        turtle.penup()
        turtle.goto(startX  + width * i, startY)
        for l in range(sizeX):

            if walls[l][i][0] ==  1:
                turtle.pendown()
            else:
                turtle.penup()
            turtle.forward(high)
    screen = turtle.Screen()
    screen.exitonclick()

当我第一次执行这个函数时,没有任何错误。但是,当我第二次执行它时,它返回turtle.Terminator。为什么会这样?

8fq7wneg

8fq7wneg1#

Turtle使用一个名为_RUNNING的变量,当调用.exitonclick()时,该变量变为false。因此,您需要在程序开始时调用turtle.Screen(),并在程序结束时调用.exitonclick()。它们都应该在函数外部调用。修改代码:

#Import necessary modules
import turtle

screen = turtle.Screen() #At beginning outside function

#Create the function to draw the maze
def printmaze(sizeX, sizeY, walls):
    startX = -300
    startY = 300

    high = (-startX // sizeX) * 2
    width = (startY // sizeY) * 2

    turtle.clear()
    turtle.speed(0)
    turtle.penup()
    turtle.goto(-startX, startY)
    turtle.pendown()
    turtle.goto(-startX, -startY)
    turtle.goto(startX, -startY)

    turtle.setheading(0)
    for i in range(sizeX):
        turtle.penup()
        turtle.goto(startX, startY - high * i)
        for l in range(sizeY):
            if walls[i][l][1] ==  1:
                turtle.pendown()
            else:
                turtle.penup()
            turtle.forward(width)

    turtle.right(90)
    for i in range(sizeY):

        turtle.penup()
        turtle.goto(startX  + width * i, startY)
        for l in range(sizeX):

            if walls[l][i][0] ==  1:
                turtle.pendown()
            else:
                turtle.penup()
            turtle.forward(high)

screen.exitonclick() #At the end outside the function

您只需在程序中调用screen = turtle.Screen().exitonclick()一次。不需要每次调用函数时都调用它们。所以,你需要把它们放在函数之外。

相关问题