python实例:用代码画五角星

最简单的方法是使用turtle库绘制五角星。1. 基础版代码通过设置画笔、颜色和填充,用for循环调用forward(100)和right(144)绘制出一个标准黄色五角星,并保持窗口显示;2. 升级版定义draw_star函数,可自定义大小、颜色和位置,在深蓝背景上绘制金色星星;3. 多星组合版利用random库随机生成位置、大小和颜色,循环绘制10颗不同样式的小星星,形成夜空效果。turtle库操作直观,适合初学者掌握绘图逻辑。

用Python画五角星,最简单的方法是使用turtle库,它内置了图形绘制功能,适合初学者快速上手。

1. 基础版:用turtle画一个五角星

以下代码会打开一个窗口,自动绘制一个标准的黄色五角星:

import turtle

创建画笔

t = turtle.Turtle() t.speed(3) t.color("yellow") t.begin_fill() t.fillcolor("yellow")

画五角星(每个角72度,外角144度)

for _ in range(5): t.forward(100) t.right(144)

t.end_fill()

隐藏画笔

t.hideturtle()

保持窗口打开

turtle.done()

2. 升级版:自定义颜色和大小

你可以调整边长、颜色和位置,让五角星更个性化:

import turtle

def draw_star(t, size, color): t.color(color) t.beginfill() t.fillcolor(color) for in range(5): t.forward(size) t.right(144) t.end_fill()

设置窗口

screen = turtle.Screen() screen.bgcolor("darkblue")

创建画笔

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

移动到画布中心偏左位置

t.penup() t.goto(-50, 0) t.pendown()

调用函数画星

draw_star(t, 150, "gold")

t.hideturtle() turtle.done()

3. 多个五角星组合

可以画多个星星,比如组成小图案或夜空效果:

import turtle
import random

t = turtle.Turtle() screen = turtle.Screen() screen.bgcolor("black") t.speed(0)

colors = ["red", "yellow", "white", "cyan", "pink"]

def draw_small_star(x, y, size): t.penup() t.goto(x, y) t.pendown() t.color(random.choice(colors)) t.beginfill() for in range(5): t.forward(size) t.right(144) t.end_fill()

画10颗随机位置的小星星

for _ in range(10): x = random.randint(-200, 200) y = random.randint(-200, 200) size = random.randint(20, 50) draw_small_star(x, y, size)

t.hideturtle() turtle.done()

基本上就这些。turtle库简单直观,适合学习绘图逻辑。只要掌握forward、right和角度计算,就能画出各种几何图形。