Skip to content Skip to sidebar Skip to footer

Close Turtle Window By X Button(close)

I'm coding Python and I'm learning Turtle. When I close turtle window by X button I'm getting an error. What can I do?

Solution 1:

Use a try - except block in each iteration of your while loop to detect when the user clicks the X button.

When the click is detected, use break to break out of the loop.

From:

import turtle

whileTrue:
    # Your game loop code
    turtle.update()

to

import turtle

whileTrue:
    try:
        # Your game loop code
        turtle.update()
    except turtle.Terminator:
        break

Solution 2:

Usually, errors generated upon closing the window via its buttons is due to abusing turtle's event module by using a while True: loop instead of timed events and other approaches.

If this the case with your program, see this answer for a detailed example of how to go about designing your code properly.

I would avoid any solutions that involve wrapping your code in a try: expression to catch the Terminator error as that's a band-aid and not a proper design. Consider:

from turtle import Screen, Turtle

def one_step():
    
    # do one iteration of useful stuff here

    screen.ontimer(one_step)


screen = Screen()

one_step()

screen.mainloop()

Post a Comment for "Close Turtle Window By X Button(close)"