简体   繁体   English

Turtle graphics - 如何控制 window 何时关闭?

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

I have a small python script which draws some turtle graphics.我有一个小的 python 脚本,它绘制了一些海龟图形。 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.当我的脚本运行完成后,乌龟屏幕会自动关闭,所以为了能够看到一段时间的图形,我必须在脚本末尾使用time.sleep(5)来延迟关闭。

Is there any way I can make this more dynamic, ie tell python that I want to control the closing of the window myself?有什么办法可以让这更加动态,即告诉 python 我想自己控制 window 的关闭? 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.我不介意脚本在等待我的命令时是否不能做任何其他事情,但如果我不需要 go 到控制台进行read()或其他操作,我会更喜欢。 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...). 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?我该如何做到这一点?

Just useturtle.done() or turtle.Screen().exitonclick() as a last command of your turtle program.只需使用turtle.done()turtle.Screen().exitonclick()作为turtle 程序的最后一个命令。

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.) (编辑:下面的hua建议的turtle.done()不那么难看。)

simply use the mainloop() function imported from turtle's module itself..只需使用从海龟模块本身导入的 mainloop() function ..

import turtle


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


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

Try adding input() at the end of your code.尝试在代码末尾添加input()

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM