精讲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()
相关推荐
岁月宁静14 小时前
五、《从零手撸 Agent》 — 什么是 Agent:从“会聊天”到“会做事”,差的就是一个循环
python·agent
梯度下降者15 小时前
Python - 函数
python·高阶函数·可调用对象·functools·嵌套作用域
starzy199017 小时前
深入理解Scala隐式参数:上下文流转
开发语言·python·scala
wuyk55518 小时前
Spider-第16讲-线程池与竞态问题
大数据·爬虫·python·elasticsearch·搜索引擎
kyle~1 天前
FastAPI --- 将业务能力以 API 的形式提供给外部系统
python·fastapi·前后端
aiotto资源分享1 天前
Python 写 JSON 文件,程序中途退出会留下什么?
java·python·json·jsondecodeerror
梯度下降者1 天前
Python信号量,条件变量,事件学习
python·条件变量·事件·信号量·线程通信
MSTcheng.1 天前
【AI应用实战】用 FastAPI + SSE 做一个自己的 AI 聊天网页:流式输出、多轮对话与完整源码
人工智能·python·大模型·fastapi·sse·ai聊天助手
the局外人1 天前
Python 实战检索优化:BM25、向量与重排
数据库·后端·python
__underline__1 天前
冷门Python知识点006篇:Python 类体里的名字,能被"凭空造出来"
后端·python