[Python] Python turtle draw filled irregular polygon based on user clicks

Discussão em 'Python' iniciado por Stack, Abril 5, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to make a program that creates a turtle window that the user can click 4 times to create an irregular polygon. It will automatically go back to the starting point after the 4th click to make sure that it is properly closed. That much works great, but the problem is that I would like to have it filled in as well, which I can't get to work.

    import turtle


    class TrackingTurtle(turtle.Turtle):
    """ A custom turtle class with the ability to go to a mouse
    click location and keep track of the number of clicks """

    def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.count = 0

    def goto_mouse(self, x, y):
    """ Go to the given (x, y) coordinates, or go back
    to the starting place after the 4th click """
    if self.count <= 4:
    self.goto(x, y)
    self.count += 1
    if self.count == 4:
    self.goto(0, 0)
    turtle.done()


    if __name__ == "__main__":
    turtle.setup(1080, 720)

    wn = turtle.Screen()
    wn.title("Polygon Fun")

    turt = TrackingTurtle()
    turt.hideturtle()

    turt.fillcolor("#0000ff")
    turt.begin_fill()
    turtle.onscreenclick(alex.goto_mouse)

    turt.end_fill()

    wn.mainloop()


    Example output

    I would like the above output to be filled in blue, but as you can see it's not. Is this possible with the turtle module? If so what might I change to fix it? Thanks in advance for your time and help!

    Continue reading...

Compartilhe esta Página