如何在 Python-Turtle 中绘制彩色填充星?
先决条件: Turtle 编程基础,在 Turtle 中绘制彩色填充形状
Turtle 是Python中的一个内置模块。它使用屏幕(纸板)和海龟(笔)提供绘图。要在屏幕上绘制一些东西,我们需要移动海龟(笔)。要移动海龟,有一些函数,即 forward()、backward() 等。
方法:
使用以下步骤:
- 进口龟
- 设置窗口画面
- 设置乌龟的颜色
- 形成一颗星
- 用颜色填充星星
下面是实现。
Python3
# importing package
import turtle
# function to draw
# colored star
def colored_star():
# size of star
size = 80
# object color
turtle.color("red")
# object width
turtle.width(4)
# angle to form star
angle = 120
# color to fill
turtle.fillcolor("yellow")
turtle.begin_fill()
# form star
for side in range(5):
turtle.forward(size)
turtle.right(angle)
turtle.forward(size)
turtle.right(72 - angle)
# fill color
turtle.end_fill()
# Driver code
colored_star()
Python3
import turtle
from random import randint
window = turtle.Screen()
turtle.bgcolor("black")
turtle.color("yellow")
turtle.speed(0)
def draw_star():
turns = 6
turtle.begin_fill()
while turns>0:
turtle.forward(25)
turtle.left(145)
turns = turns-1
turtle.end_fill()
nums_stars = 0
while nums_stars <50:
x=randint(-300,300)
y=randint(-300,300)
draw_star()
turtle.penup()
turtle.goto(x,y)
turtle.pendown()
nums_stars = nums_stars + 1
window.exitonclick()
输出 :
因为,到目前为止,您一定已经学会了如何在星星上绘制和填充颜色。所以,让我们用这些知识尝试一些独特的东西。让我们用一些创意和编程来打造一个充满星星的夜晚。
Python3
import turtle
from random import randint
window = turtle.Screen()
turtle.bgcolor("black")
turtle.color("yellow")
turtle.speed(0)
def draw_star():
turns = 6
turtle.begin_fill()
while turns>0:
turtle.forward(25)
turtle.left(145)
turns = turns-1
turtle.end_fill()
nums_stars = 0
while nums_stars <50:
x=randint(-300,300)
y=randint(-300,300)
draw_star()
turtle.penup()
turtle.goto(x,y)
turtle.pendown()
nums_stars = nums_stars + 1
window.exitonclick()
输出: