精讲Python之turtle库(二):设置画笔颜色、回旋伞、变色回旋伞、黄色三角形、五角星,附源代码

精讲Python之turtle(海龟)库(一):原理及例子精讲-CSDN博客,这篇文章已经介绍了turtle库的基本知识点,现对进阶的功能进行讲解。

1、设置画笔颜色

python 复制代码
pen.pencolor(color)

使用rgb模式的颜色,rgb模式的颜色几乎包括了人类视力所能感知的所有颜色

rgb用3个0~255数字表示颜色,例如(0,0,0),(100,20,50),(255,255,255)

第一个数字r表示红色的比重

第二个数字g表示绿色的比重

第三个数字b表示蓝色的颜色

当三个数字都是0的时候,0,0,0表示黑色

当三个数字是最大值时:255,255,255,表示白色

255,0,0-红色(亮)

100,0,0-红色(暗)

255,255,0-黄色(红色+绿色=黄色)

设置turtle的rgb颜色:

python 复制代码
turtle.colormode(255)

设置笔的颜色:

python 复制代码
pen.pencolor(r,g,b)

渐变颜色代码,每画完一笔就修改颜色

例子1

python 复制代码
import turtle
pen = turtle.Turtle()
turtle.colormode(255)
pen.pd()
r=250
g=50
b=150
cd=25
for i in range(33):
    for j in range(2):
        pen.pencolor(r,g,b)
        pen.forward(cd)
        pen.right(89)
        r -=3
        g +=3
        b+=2
    cd+=5
turtle.done()

填充色:设置填充颜色pen.fillcolor('yellow')
例子2:画一个填充黄色的三角形

python 复制代码
import turtle
pen = turtle.Turtle()
pen.pd()
pen.fillcolor('yellow')
pen.begin_fill()
for i in range(3):
    pen.forward(200)
    pen.right(120)
pen.end_fill()
turtle.done()

例子3:turtle如何画一个回旋伞

python 复制代码
import turtle
pen = turtle.Turtle()
pen.pd()
cd = 200
for i in range(50):
    pen.fillcolor('yellow')
    pen.begin_fill()
    for i in range(3):
        pen.forward(cd)
        pen.right(120)
    pen.end_fill()
    pen.right(20)
    cd = cd-3
turtle.done()

例子4: 渐变颜色的回旋伞

python 复制代码
import turtle
pen = turtle.Turtle()
pen.pd()
cd = 120
turtle.colormode(255)
r=200
g=200
b=50
cd=200
for i in range(50):
    pen.pencolor(r,g,b)
    pen.fillcolor(r,g,b)
    pen.begin_fill()
    for i in range(3):
        pen.forward(cd)
        pen.right(120)
    pen.end_fill()
    pen.right(20)
    r-=4
    g-=2
    b+=3
    cd = cd-3
turtle.done()

例子5:画五角星

python 复制代码
import turtle
pen = turtle.Turtle()
pen.pd()
for i in range(5):
    pen.forward(100)
    pen.right(144)
turtle.done()
相关推荐
cup115 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi007 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵9 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf10 小时前
Agent 流程编排
后端·python·agent
copyer_xyf10 小时前
Agent RAG
后端·python·agent
copyer_xyf11 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf11 小时前
Agent 记忆管理
后端·python·agent
星云穿梭1 天前
用Python写一个带图形界面的学生管理系统——完整教程
python
金銀銅鐵1 天前
用 Pygame 实现 15 puzzle
python·数学·游戏