Function 你能用函数返回海龟吗?
有没有办法使用一个函数来创建一个海龟,然后将海龟返回到一个单独的函数中使用Function 你能用函数返回海龟吗?,function,return,turtle-graphics,python-turtle,Function,Return,Turtle Graphics,Python 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.begi
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)
我有一个任务是制作一个正方形马赛克,我有一个main
函数、create\u turtle
函数和draw\u square
函数。当我运行我的程序时,它的工作方式应该是这样的,但是正如您所看到的,我没有使用create\u turtle
函数。我刚刚在我的main
函数中创建了海龟
有没有一种方法可以调用我的create\u turtle
函数并以某种方式将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)
忘了提到,在这段代码之后,我只调用main()函数,在使用任何
def
语句之前,它会调用draw_square()函数。这时你可以指定你的海龟。但是,您必须在每个def
语句中使用global(海龟名称)
。