【问题标题】:Filling a shape with color in python turtle在 python turtle 中用颜色填充形状
【发布时间】:2017-11-13 15:22:15
【问题描述】:

我正在尝试用颜色填充形状,但是当我运行它时,它没有显示。 我不应该为此使用课程吗?我不精通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()

【问题讨论】:

    标签: python python-3.x turtle-graphics


    【解决方案1】:

    您的程序的问题:您创建并设置了您实际上不使用的海龟的速度; 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()
    

    【讨论】:

    • 当我尝试运行程序时,我不断收到错误消息:“NotImplementedError: super is not yet implemented, please report your use case as a github issue. on line 5”。我如何实现 super()
    • @geek2001,尝试将Turtle.__init__(self, visible=False) 替换为super().__init__(visible=False) 行。由于您标记了您的问题 Python-3.x,因此我使用了较新的语法。
    • 如何在新标签页中运行它并将其添加到其他代码中?
    • @geek2001,我不确定你在问什么,但根据你的原始代码,我猜答案是,“删除最后两行。”
    • 我会换一种说法。有没有办法在不重新输入所有文件的情况下在新文件中运行它。
    猜你喜欢
    • 2016-03-13
    • 2018-06-15
    • 1970-01-01
    • 2014-05-26
    • 2014-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-27
    相关资源
    最近更新 更多