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

用Python画五角星,最简单的方法是使用turtle库,它内置了图形绘制功能,适合初学者快速上手。
以下代码会打开一个窗口,自动绘制一个标准的黄色五角星:
import turtle
<h1>创建画笔</h1><p>t = turtle.Turtle()
t.speed(3)
t.color("yellow")
t.begin_fill()
t.fillcolor("yellow")</p><h1>画五角星(每个角72度,外角144度)</h1><p>for _ in range(5):
t.forward(100)
t.right(144)</p><p>t.end_fill()</p><h1>隐藏画笔</h1><p>t.hideturtle()</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p><h1>保持窗口打开</h1><p>turtle.done()</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/735">
<img src="https://img.php.cn/upload/ai_manual/001/246/273/68b6cdbf48df2598.png" alt="代码小浣熊">
</a>
<div class="aritcle_card_info">
<a href="/ai/735">代码小浣熊</a>
<p>代码小浣熊是基于商汤大语言模型的软件智能研发助手,覆盖软件需求分析、架构设计、代码编写、软件测试等环节</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="代码小浣熊">
<span>51</span>
</div>
</div>
<a href="/ai/735" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="代码小浣熊">
</a>
</div>
你可以调整边长、颜色和位置,让五角星更个性化:
import turtle
<p>def draw_star(t, size, color):
t.color(color)
t.begin<em>fill()
t.fillcolor(color)
for </em> in range(5):
t.forward(size)
t.right(144)
t.end_fill()</p><h1>设置窗口</h1><p>screen = turtle.Screen()
screen.bgcolor("darkblue")</p><h1>创建画笔</h1><p>t = turtle.Turtle()
t.speed(5)</p><h1>移动到画布中心偏左位置</h1><p>t.penup()
t.goto(-50, 0)
t.pendown()</p><h1>调用函数画星</h1><p>draw_star(t, 150, "gold")</p><p>t.hideturtle()
turtle.done()</p>可以画多个星星,比如组成小图案或夜空效果:
import turtle
import random
<p>t = turtle.Turtle()
screen = turtle.Screen()
screen.bgcolor("black")
t.speed(0)</p><p>colors = ["red", "yellow", "white", "cyan", "pink"]</p><p>def draw_small_star(x, y, size):
t.penup()
t.goto(x, y)
t.pendown()
t.color(random.choice(colors))
t.begin<em>fill()
for </em> in range(5):
t.forward(size)
t.right(144)
t.end_fill()</p><h1>画10颗随机位置的小星星</h1><p>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)</p><p>t.hideturtle()
turtle.done()</p>基本上就这些。turtle库简单直观,适合学习绘图逻辑。只要掌握forward、right和角度计算,就能画出各种几何图形。
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号