海龟图形 - 如何控制窗口关闭时间?
我有一个小的Python脚本,它用海龟图形库画图。当我的脚本运行完毕后,海龟的窗口会自动关闭,所以为了能多看一会儿图形,我在脚本最后加了time.sleep(5)
,让它延迟关闭。
有没有办法让我更灵活一点,也就是说,让Python知道我想自己控制窗口的关闭?我不介意脚本在等待我的命令时不能做其他事情,但我希望不需要去控制台输入read()
之类的命令。理想情况下,画布应该在脚本结束后仍然保持打开,但我也可以接受一种解决方案,就是脚本暂停,直到我关闭画布窗口(或者点击画布,或者其他什么操作...)。
我该怎么做呢?
5 个回答
12
简单来说,就是直接使用从turtle模块里导入的mainloop()函数就可以了!
import turtle
#Draw a square
for i in range(4):
turtle.forward(200)
turtle.left(90)
#calling for the mainloop()
turtle.mainloop()
27
import turtle
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
# etc.
turtle.getscreen()._root.mainloop() # <-- run the Tkinter main loop
(编辑:下面hua建议的turtle.done()
看起来更好一些。)
98
只需在你的海龟程序的最后一行使用 turtle.done()
或者 turtle.Screen().exitonclick()
。