首页 > 解决方案 > 你能用函数返回乌龟吗?

问题描述

有没有办法使用一个函数来创建一个乌龟,然后返回乌龟以在一个单独的函数中使用?

我的任务是制作正方形马赛克,我有一个main功能,create_turtle功能和draw_square功能。当我运行我的程序时,它按照预期的方式工作,但正如你所看到的,我没有使用该create_turtle功能。我刚刚在我的main函数中创建了海龟。

有没有办法可以调用我的create_turtle函数并以某种方式将海龟返回到我的主函数?

def draw_square(rectangle, x, y, width, height):
    rectangle.penup()
    rectangle.goto(x,y)
    rectangle.fillcolor(random.random(), random.random(), random.random())
    rectangle.pendown()
    rectangle.begin_fill()
    for sides in range(2):
        rectangle.forward(width)
        rectangle.right(90)
        rectangle.forward(height)
        rectangle.right(90)
    rectangle.end_fill()
    rectangle.penup()
    rectangle.goto(x+(width/2),y-(height/2))
    rectangle.stamp()

def create_turtle():
    stampy = turtle.Turtle()
    stampy.shape("turtle")
    stampy.hideturtle()
    stampy.speed(0)
    return(stampy)

def main():
    height = turtle.window_height()
    width = turtle.window_width()
    rows = int(input("Enter the number of rows for the mosaic: "))
    columns = int(input("Enter the number of columns for the mosaic: "))
    stampy = turtle.Turtle()
    stampy.shape("turtle")
    stampy.hideturtle()
    stampy.speed(0)
    y = height/2
    for row in range(rows):
        x = width/(-2)
        for column in range(columns):
            draw_square(stampy, x, y, width/columns, height/rows)
            x = x + (width/columns)
        y = y - (height/rows)

标签: functionreturnturtle-graphicspython-turtle

解决方案


推荐阅读