Turtle graphics - How do I control when the window closes?

末鹿安然 提交于 2019-11-27 12:01:09

问题


I have a small python script which draws some turtle graphics. When my script has finished running, the turtle screen automatically closes, so to be able to see the graphics for a while I have to use time.sleep(5) at the end of the script to delay the closing.

Is there any way I can make this more dynamic, i.e. tell python that I want to control the closing of the window myself? I don't mind if the script can't do anything else while waiting for my command, but I'd prefer if I didn't have to go to the console for a read() or something. Ideally, the canvas should stay open even after the script finishes running, but I am OK with a solution that halts the script until I close the window that holds the canvas (or click the canvas, or whatever...).

How do I accomplish this?


回答1:


Just use turtle.done() or turtle.Screen().exitonclick() as a last command of your turtle program.




回答2:


import turtle

turtle.forward(100)
turtle.left(90)
turtle.forward(100)
# etc.

turtle.getscreen()._root.mainloop()  # <-- run the Tkinter main loop

(edit: turtle.done() as suggested by hua below is less ugly.)




回答3:


simply use the mainloop() function imported from turtle's module itself!.

import turtle


#Draw a square
for i in range(4):
    turtle.forward(200)
    turtle.left(90)


#calling for the mainloop()
turtle.mainloop()



回答4:


Try adding input() at the end of your code.




回答5:


This waits for several clicks - and draws a spiral while you click - until it decides to exit on the last click:

import turtle


win = turtle.Screen()
win.bgcolor("white")

tess = turtle.Turtle()

tess.speed(0)
tess.color("blue")             
tess.pensize(5)                 
offSet=30

def doNextEvent(x,y):

    global offSet
    global win
    tess.forward(20)
    tess.left(1+offSet)
    offSet=offSet-2
    if(offSet<1):
        win.exitonclick()


win.onclick(doNextEvent)
win.listen()
win.mainloop()


来源:https://stackoverflow.com/questions/6234798/turtle-graphics-how-do-i-control-when-the-window-closes

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