[英]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.