Skip to main content
 首页 » 编程设计

python之在 python turtle 中用颜色填充形状

2024年10月01日6daizhj

我试图用一种颜色填充一个形状,但是当我运行它时,它没有显示。 我不应该为此使用类(class)吗?我不精通 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() 

请您参考如下方法:

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