Search code examples
pythonpython-3.xturtle-graphicspython-turtle

Filling a star shape with Turtle


I'm new to Python and I'm learning graphics using turtle. I'm attempting to color a star I've drawn, but the color won't fill for every part of the star.

Here is my code:

def red_star():
    f.penup()
    f.goto(145,-130)
    
    f.fillcolor("red")
    f.begin_fill()
    
    for i in range(5):
        f.fd(100)
        f.rt(144)
    
    f.end_fill()
    f.pendown()

red_star()

Here is what I produce when I run the program:

Image of star


Solution

  • It's documented in turtle.end_fill() that:

    Whether or not overlap regions for self-intersecting polygons or multiple shapes are filled depends on the operating system graphics, type of overlap, and number of overlaps.

    Draw the outer edge of the star so it is not a self-intersecting polygon:

    import turtle
    
    def red_star(t, side):
        t.fillcolor('red')
        t.pencolor('black')  # to highlight the lines
        t.pendown()
        t.width(3)
        t.begin_fill()
        for i in range(5):
            t.fd(side)
            t.left(72)
            t.forward(side)
            t.right(144)
        t.end_fill()
    
    t = turtle.Turtle()
    s = t.screen
    s.delay(0)
    t.hideturtle()
    t.penup()
    red_star(t, 50)
    s.exitonclick()
    s.mainloop()
    

    Output:

    Filled Star