问题
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?
回答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
while True:
# Your game loop code
turtle.update()
to
import turtle
while True:
try:
# Your game loop code
turtle.update()
except turtle.Terminator:
break
回答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()
来源:https://stackoverflow.com/questions/65197470/close-turtle-window-by-x-buttonclose