Python 乌龟 end_poly() 不起作用

Python turtle end_poly() does not work

Turtle 文档说何时达到 end_poly()

Stop recording the vertices of a polygon. Current turtle position is last vertex of polygon. This will be connected with the first vertex.

在我的例子中,最后一条线不是从最后一个顶点绘制回第一个顶点。它在 2.7 和 3.7 Python 中的作用相同。

from turtle import *

print("position 0:",position())
width(5)
pencolor("red")
fillcolor("blue")
begin_fill()
begin_poly()
fd(100)
print("position 1:",position())
left(90)
fd(100)
print("position 2:",position())
end_poly()
end_fill()

p = get_poly()
print("poly p:",p)
register_shape("myShape",p)
shapes_ = getshapes()
print("shapes_:", shapes_)

输出:

position 0: (0.00,0.00)
position 1: (100.00,0.00)
position 2: (100.00,100.00)
poly p: ((0.00,0.00), (100.00,0.00), (100.00,100.00))
shapes_: ['arrow', 'blank', 'circle', 'classic', 'myShape', 'square', 'triangle', 'turtle']

Image of polygon

我认为这是文档中的错误,但可以理解。

首先,明明自己合图就能画出自己想要的东西:

from turtle import Turtle, Screen

screen = Screen()
turtle = Turtle(visible=False)

turtle.width(5)
turtle.color("red", "blue")

position = turtle.position()

turtle.begin_fill()
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.goto(position)
turtle.end_fill()

screen.exitonclick()

那么多边形有什么用呢?好吧,除非您自己实现代码,否则默认情况下 turtle 无法对多边形执行任何操作,除了将它们用作 turtle 游标。在这种情况下,它会将它们传递给负责关闭多边形的 tkinter:

from turtle import Turtle, Screen

screen = Screen()
turtle = Turtle(visible=False)
turtle.penup()

turtle.begin_poly()
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.end_poly()

screen.register_shape("myShape", turtle.get_poly())

turtle.shape("myShape")  # when the polygon gets closed
turtle.shapesize(outline=5)
turtle.color("red", "blue")

turtle.stamp()

screen.exitonclick()

(我猜它在 tkinter 的 canvas.coords() 中多边形被关闭的地方。)请注意,您的 width(5) 在这种情况下没有任何意义, *_fill() 也没有作为光标的轮廓宽度使用 shapesize() 设置,光标自然填充。它不需要在创建多边形时指定颜色,您可以等到部署新光标。

我相信 end_poly() 文档中的这个声明:

last vertex of polygon. This will be connected with the first vertex.

真正应该位于 turtle 的 register_shape() 文档的多边形部分。但是您可以将错误理解为乌龟只认为 *_poly() 的作用是用于创建新游标。而多边形应该是第一个 class,turtle 中的灵活数据类型。