Close turtle window by X button(close)

对着背影说爱祢 提交于 2021-02-17 05:18:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!