Simon Simon - 1 month ago 12
Python Question

Python Turtle Graphics Filling a Non-Closed Polygon

I thought (assumed) that the begin_fill()/end_fill() commands would only "fill" a shape if the shape was "closed". Consider the following:
import turtle

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


Python completes the figure and fills it in - which is not what I want. How do I ensure that only a closed polygon will be filled in?

Answer

I guess we could subclass Turtle and change the rules:

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()

Now we can do:

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()

enter image description here

Warning, this solution is fragile! It depends on knowledge of the underlying implementation which might change in a future release. But if you absolutely gotta have it...