首页 > 解决方案 > 关于 Turtle 中的循环

问题描述

我想问一个关于我试图在我的程序中使用的某种循环的问题。因此,为此,我将分享我的程序中存在的用于绘制三角形的函数代码;

def drawing_triangle():

    turtle.forward(50)
    turtle.left(120)
    turtle.forward(50)
    turtle.left(120)
    turtle.forward(50)
    turtle.left(120)
    turtle.penup()
    turtle.forward(50)
    turtle.forward(10)
    turtle.pendown()

所以这是绘制三角形的功能,当我尝试运行程序时,它会给出如下输出;

output_theoneiget

正如您在图片中看到的,它并排打印三角形,但我希望它们在每四个三角形开始一个新行,如下图所示;

output_theoneiwant

总之,我的问题是如何获得第二张图片中的输出?

提前致谢。

标签: pythonpython-3.xturtle-graphics

解决方案


Have you tried reading over the docs for the turtle package yet? https://docs.python.org/3.7/library/turtle.html

I think the difficulty you're having comes from all the turtle's motion being relative to its current position. But for making a new "triangle line", you want to "reset" the turtle's position all the way back to the left.

Take a look at the command turtle.setposition(x, y) -- this sets the turtle's location in an absolute manner. Instead of moving relative to where it currently is, it just "jumps" to (x, y).

You could place that command in part of a for-loop after you've drawn a series of triangles to reset to the left. You'll have to manage your for-loop to iteratively set the height so each subsequent row is placed below the last, but that's the only real difficulty.

Alternatively, you could count how many triangles you've drawn so far in a given "triangle line", then relatively re-position backwards by moving left based on width/spacing and how many triangles have been drawn so far. But I think absolute positioning is probably the easier approach and a good technique to get used to anyway.


推荐阅读