Python 海龟图形填充非闭合多边形

Python Turtle Graphics Filling a Non-Closed Polygon

我认为(假设)如果形状是 "closed",begin_fill()/end_fill() 命令只会 "fill" 一个形状。考虑以下: 导入海龟

turtle.color("red")
turtle.begin_fill()
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.end_fill()

Python 完成图形并填写 - 这不是我想要的。如何确保只填充封闭的多边形?

我想我们可以继承 Turtle 并更改规则:

from turtle import Turtle, Screen

class Yertle(Turtle):
    def end_fill(self):
        if len(self._fillpath) > 3 and self._fillpath[0] == self._fillpath[-1]:
            super().end_fill()  # warning, Python3 syntax!
        else:
            self.end_poly()

现在我们可以做:

turtle = Yertle()
screen = Screen()

turtle.color("red")

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

turtle.penup()
turtle.home()
turtle.pendown()

turtle.color("green")

turtle.begin_fill()
turtle.backward(100)
turtle.right(90)
turtle.backward(100)
turtle.home()
turtle.end_fill()

screen.exitonclick()

警告,此解决方案脆弱!它取决于对底层实现的了解,这可能会在未来的版本中发生变化。但如果你绝对必须拥有它......