[英]Python turtle draw filled irregular polygon based on user clicks
我想制作一個程序來創建一個海龜 window,用戶可以單擊 4 次來創建一個不規則多邊形。 第 4 次點擊后,它會自動 go 回到起點,以確保它正確關閉。 這么多效果很好,但問題是我也想把它填滿,我無法開始工作。
import turtle
class TrackingTurtle(turtle.Turtle):
""" A custom turtle class with the ability to go to a mouse
click location and keep track of the number of clicks """
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.count = 0
def goto_mouse(self, x, y):
""" Go to the given (x, y) coordinates, or go back
to the starting place after the 4th click """
if self.count <= 4:
self.goto(x, y)
self.count += 1
if self.count == 4:
self.goto(0, 0)
turtle.done()
if __name__ == "__main__":
turtle.setup(1080, 720)
wn = turtle.Screen()
wn.title("Polygon Fun")
turt = TrackingTurtle()
turt.hideturtle()
turt.fillcolor("#0000ff")
turt.begin_fill()
turtle.onscreenclick(alex.goto_mouse)
turt.end_fill()
wn.mainloop()
我希望將上面的 output 填充為藍色,但如您所見,事實並非如此。 龜模塊可以做到這一點嗎? 如果是這樣,我可以改變什么來解決它? 提前感謝您的時間和幫助!
你很接近。 誤解似乎是認為onscreenclick
阻塞直到形狀完成,然后end_fill()
運行。 實際上, onscreenclick
在注冊點擊處理程序后立即返回,然后.end_fill()
在任何點擊發生或龜主循環運行之前運行。 當用戶開始點擊時,填充早已關閉。
解決方案是將.end_fill()
調用移至if self.count == 4:
塊。
由於我不喜歡繼承Turtle
,因此這里有一個類似的最小示例,它使用了閉包,但應該很容易適應您的用例。
import turtle
def track_polygon(sides=5):
def goto_mouse(x, y):
nonlocal clicks
if clicks < sides - 1:
turtle.goto(x, y)
clicks += 1
if clicks >= sides - 1:
turtle.goto(0, 0)
turtle.end_fill()
turtle.exitonclick()
clicks = 0
turtle.begin_fill()
turtle.onscreenclick(goto_mouse)
track_polygon()
turtle.mainloop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.