Question

I am working on using python turtle to draw a five -star.But I need to clear the screen and redraw it after I click it. So the process like this :

Blank Screen

  1. Click mouse
  2. Start drawing star
  3. finish
  4. click mouse
  5. clear screen and re draw

Thanks

import turtle
wn = turtle.Screen()

tess = turtle.Turtle()
tess.hideturtle()

tess.left(36)
tess.forward(100)
for a in range(4):
    tess.left(144)
    tess.forward(100)
Was it helpful?

Solution

For events like mouse_click to work, you must run the turtle in an (infinite) loop. Now, it will listen to the events & process accordingly.

To run such a loop, do wn.mainloop()

For detailed info on all of turtle, go here - http://docs.python.org/3.1/library/turtle.html#turtle.clear

Here you go. Most of the explanation is commented accordingly.

import turtle
wn = turtle.Screen()

tess = turtle.Turtle()

def draw(x, y): # x, y are mouse position arguments passed by onclick()

    tess.clear() # Clear out the drawing (if any)
    tess.reset() # Reset the turtle to original position
    tess.hideturtle()

    tess.left(36)
    tess.forward(100)
    for a in range(4):
        tess.left(144)
        tess.forward(100)
    tess.right(36) # to go to original place

draw(0, 0) # Draw the first time

wn.onclick(draw) # Register function draw to the event mouse_click
wn.onkey(wn.bye, "q") # Register function exit to event key_press "q"

wn.listen() # Begin listening to events like key_press & mouse_clicks
wn.mainloop()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top