Python Turtle: Function to draw left nested squares

I am trying to write a function to draw nested squares. The picture must consist of 10 squares. The outermost is 200 wide, each inner one is 20 smaller. They are on the left and top 5 apart. It needs to start with reset() and hideturtle() and use loops. I am having trouble with setting the positioning for the drawing of each square, since the turtle needs to move to the right 5 pixels and down 5 pixels for each one. The function should return an image that looks like the one below. This is what I have so far:

def ForTheSquares(t, center, side):
    xPt =center[0]+(side-(side-5)) 
    yPt = center[0]-(side-(side-5))
    t.up()
    t.goto(xPt, yPt)
    t.down
    for i in range(4):
        t.forward(side)
        t.right(90)


def NestSquares(t, center, side):
    if side <1:
        return
    ForTheSquares(t, center, side)
    NestSquares(t, center, side-20)


def main():
    t=turtle.Turtle()
    NestSquares(t, [0,0], 200)

This is my goal:

嵌套广场目标

Any help would be very much appreciated! I am new to coding and Python.


Look at the algebra in your starting coordinates:

xPt =center[0]+(side-(side-5)) 

This reduces to

xPt = center[0] - 5

... which is not what you wanted, right?

Is there any reason why you're keying on the square's center? Among other things, you've failed to move the square's center coordinates when you draw the next smaller square.

Would it not be easier to use the upper-left corner each time (not the center), and then recur with

ForTheSquares(t, old_corner, side)
new_corner = (old_corner[0]+5, old_corner[1]+5)
NestSquares(t, new_corner, side-20)

Of course, you also need to draw from that NW corner, but that should actually be easier.

Is that enough to get you moving?


This is another program that becomes much simpler if you think of it as a stamping problem instead of a drawing problem:

import turtle

turtle.reset()  # not necessary but a stated requirement
turtle.hideturtle()

turtle.shape("square")
turtle.fillcolor("white")

for side in range(200, 0, -20):
    turtle.shapesize(side / 20)
    turtle.stamp()
    x, y = turtle.position()
    turtle.setposition(x - 5, y + 5)

turtle.exitonclick()

It runs from large to small as otherwise the stamps would obscure each other:

链接地址: http://www.djcxy.com/p/80708.html

上一篇: 用Python递归正方形

下一篇: Python Turtle:绘制左嵌套正方形的函数