Search code examples
pythonturtle-graphics

Exit on click no longer works after using clearscreen


I'm working on a Python Turtle graphics program and I'm trying to use the exitonclick method to close the window when it's clicked. However, it doesn't seem to be working.

from turtle import Turtle, Screen

rem = Turtle()
screen = Screen()


rem.fd(70)

def clear():
    screen.clearscreen()

screen.listen()

screen.onkey(fun=clear,key = "c")

screen.exitonclick()

When I run it and try to exit the program by clicking in the screen it works fine and quits but when I press c and cleared the screen then if I try to exit by clicking nothing happens.


Solution

  • screen.clearscreen() completely resets the window. That includes removing all modifications to it made through exitonclick. The easiest solution is just to call exitonclick again in your custom function:

    from turtle import Turtle, Screen
    
    rem = Turtle()
    screen = Screen()
    
    rem.fd(70)
    
    def clear():
        screen.clearscreen()
        screen.exitonclick()
    
    screen.listen()
    
    screen.onkey(fun=clear,key = "c")
    
    screen.exitonclick()