繁体   English   中英

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

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

我有一个小的 python 脚本,它绘制了一些海龟图形。 当我的脚本运行完成后,乌龟屏幕会自动关闭,所以为了能够看到一段时间的图形,我必须在脚本末尾使用time.sleep(5)来延迟关闭。

有什么办法可以让这更加动态,即告诉 python 我想自己控制 window 的关闭? 我不介意脚本在等待我的命令时是否不能做任何其他事情,但如果我不需要 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...).

我该如何做到这一点?

只需使用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

(编辑:下面的hua建议的turtle.done()不那么难看。)

只需使用从海龟模块本身导入的 mainloop() function ..

import turtle


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


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

尝试在代码末尾添加input()

这会等待几次点击 - 并在您点击时绘制一个螺旋线 - 直到它决定在最后一次点击时退出:

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