Python 海龟根据用户点击绘制填充的不规则多边形

问题描述 投票:0回答:1

我想制作一个程序,创建一个海龟窗口,用户可以单击 4 次来创建不规则的多边形。第 4 次点击后,它将自动返回起点,以确保其正确关闭。这么多,效果很好,但问题是我也想把它填满,但我无法开始工作。

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()

Example output

我希望上面的输出被填充为蓝色,但正如你所看到的,它不是。海龟模块可以做到这一点吗?如果是这样我可以改变什么来解决它?预先感谢您的时间和帮助!

python turtle-graphics python-turtle
1个回答
0
投票

你已经很接近了。误解似乎是认为

onscreenclick
会阻塞,直到形状完成,然后
end_fill()
运行。实际上,
onscreenclick
在注册点击处理程序后立即返回,然后
.end_fill()
在发生任何点击或乌龟主循环运行之前运行。当用户开始点击时,填充早已关闭。

解决方案是将

.end_fill()
调用移至
if self.count == 4:
块。

因为我不喜欢继承

Turtle
,所以这里有一个类似的最小示例,它使用闭包,但应该很容易适应您的用例。

from turtle import Screen, Turtle


def track_polygon(t, sides=5):
    def goto_mouse(x, y):
        nonlocal clicks

        if clicks < sides - 1:
            t.goto(x, y)
            clicks += 1

            if clicks >= sides - 1:
                t.goto(0, 0)
                t.end_fill()
                Screen().exitonclick()

    clicks = 0
    t.begin_fill()
    Screen().onscreenclick(goto_mouse)


track_polygon(Turtle())
Screen().mainloop()
© www.soinside.com 2019 - 2024. All rights reserved.