海龟图形 - 如何控制窗口何时关闭?
我有一个小的 python 脚本,可以绘制一些海龟图形。当我的脚本运行完毕后,海龟屏幕会自动关闭,因此为了能够看到图形一段时间,我必须在脚本末尾使用 time.sleep(5)
来延迟关闭。
有什么办法可以让它更加动态,即告诉 python 我想自己控制窗口的关闭?我不介意脚本在等待我的命令时是否不能执行任何其他操作,但我更希望不必转到控制台进行 read()
或其他操作。理想情况下,即使在脚本完成运行后,画布也应该保持打开状态,但我可以接受一个解决方案,该解决方案可以停止脚本,直到我关闭保存画布的窗口(或单击画布,或其他...)。
我该如何实现这个目标?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
只需使用
turtle.done()
或turtle.Screen().exitonclick()
作为海龟程序的最后一个命令。Just use
turtle.done()
orturtle.Screen().exitonclick()
as a last command of your turtle program.(编辑:
turtle.done()
正如下面 hua 所建议的那样,没那么难看。)(edit:
turtle.done()
as suggested by hua below is less ugly.)只需使用从turtle模块本身导入的mainloop()函数即可!
simply use the mainloop() function imported from turtle's module itself!.
尝试在代码末尾添加
input()
。Try adding
input()
at the end of your code.这将等待几次单击 - 并在您单击时绘制螺旋 - 直到它决定在最后一次单击时退出:
This waits for several clicks - and draws a spiral while you click - until it decides to exit on the last click: