使用Python Turtle在形状内填充颜色

3
我试图给一个形状填充颜色,但运行时并没有显示出来。 我不能使用类吗?我对Python-3不熟练,仍在学习如何使用类。
import turtle

t=turtle.Turtle()
t.speed(0)


class Star(turtle.Turtle):
    def __init__(self, x=0, y=0):
        turtle.Turtle.__init__(self)
        self.shape("")
        self.color("")
#Creates the star shape    
    def shape(self, x=0, y=0):
        self.fillcolor("red")
        for i in range(9):
        self.begin_fill()
        self.left(90)
        self.forward(90)
        self.right(130)
        self.forward(90)
        self.end_fill()
#I was hoping this would fill the inside        
    def octagon(self, x=0.0, y=0.0):
        turtle.Turtle.__init__(self)

    def octa(self): 
        self.fillcolor("green")
        self.begin_fill()
        self.left(25)
        for x in range(9):
            self.forward(77)
            self.right(40)

#doesn't run with out this
a=Star()
1个回答

3

你的程序存在以下问题:你创建并设置了一只没有实际使用的海龟的速度;turtle.py已经有一个shape()方法,所以不要覆盖它以表示其他含义,选择一个新名称;你不希望begin_fill()end_fill()在循环内部,而是将其包围在循环外部;你使用无效参数调用自己的shape()方法。

以下重新编写的代码解决了上述问题:

from turtle import Turtle, Screen

class Star(Turtle):
    def __init__(self, x=0, y=0):
        super().__init__(visible=False)
        self.speed('fastest')
        self.draw_star(x, y)

    def draw_star(self, x=0, y=0):
        """ Creates the star shape """

        self.penup()
        self.setposition(x, y)
        self.pendown()

        self.fillcolor("red")

        self.begin_fill()

        for _ in range(9):
            self.left(90)
            self.forward(90)
            self.right(130)
            self.forward(90)

        self.end_fill()

t = Star()

screen = Screen()
screen.exitonclick()

enter image description here


当我尝试运行程序时,我一直收到错误提示:“NotImplementedError: super尚未实现,请将您的用例作为github问题报告。在第5行。” 我该如何实现super()? - geek2001
@geek2001,尝试将Turtle.__init__(self, visible=False)替换为super().__init__(visible=False)这一行。由于您标记了Python-3.x,我使用了更新的语法。 - cdlane
我该如何在新标签页中运行它并将其添加到其他代码中? - geek2001
@geek2001,我不确定你在问什么,但根据你的原始代码,我猜答案是:“删除最后两行。” - cdlane
我来换个说法。有没有一种方法可以在新文件中运行它,而不必重新输入所有内容。 - geek2001
@geek2001,我明白了。删除最后三行代码(或使用if __name__ == "__main__":语句将其隔离)。将此代码保存为star.py(或其他名称),然后在您的其他Python文件中执行:from star import Star。然后,您可以执行t = Star()来生成一个新的星星。 - cdlane

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接