Turtle window not closing

Peter Otten __peter__ at web.de
Sun Apr 23 03:05:22 EDT 2017


Harshika Varadhan via Python-list wrote:

> Thank you for your response. I apologize for that, this is my first time
> posting so I wasn't sure how to copy my code! I figured out that using the
> clear() method works for clearing the turtle window after drawing the game
> board, but now I am trying to figure out how to make the program wait a
> few seconds or wait for the user to press a key before clearing the turtle
> window (not closing the window, just clearing it). Is there any way to do
> this?

I experimented a bit and found the Screen.ontimer() and onkey() methods. 
Those take a function (a "callback") that will be executed after a certain 
time or when the specified key is pressed. Here are two simple example 
scripts:

demo_turtle_timer.py
# Draw a square, then remove it after two seconds
import turtle

def draw_board():
    myturtle.showturtle()

    # draw a square
    # replace with your code
    for i in range(4):
        myturtle.forward(100)
        myturtle.right(90)

def clear_board():
    myturtle.clear()
    myturtle.hideturtle()

myturtle = turtle.Turtle()
screen = turtle.Screen()

draw_board()

# clear board after 2 seconds
screen.ontimer(clear_board, 2000)

screen.mainloop()

demo_turtle_key.py
# Hit d to draw a square, then hit c to remove it
import turtle

def draw_board():
    myturtle.showturtle()

    # draw a square
    # replace with your code
    for i in range(4):
        myturtle.forward(100)
        myturtle.right(90)

def clear_board():
    myturtle.clear()
    myturtle.hideturtle()

myturtle = turtle.Turtle()
screen = turtle.Screen()

# invoke clear_board() when the c key is pressed
screen.onkey(clear_board, "c")

# invoke draw_board() when the d key is pressed
screen.onkey(draw_board, "d")

screen.listen()
screen.mainloop()




More information about the Python-list mailing list