Python海龟绘图(Turtle Graphics)核心函数和关键要点

以下是Python海龟绘图(Turtle Graphics)的核心函数和关键要点整理:


一、画布设置

函数/方法 说明 参数说明 备注
turtle.setup(width, height, x, y) 设置画布尺寸和位置 width=宽度,height=高度,x/y=窗口左上角坐标 默认尺寸800x600,默认居中(x=0, y=0)
turtle.clear() 清除画布内容 - 仅清除图像,保留画笔属性
turtle.reset() 重置画布和画笔 - 恢复默认属性(位置、颜色、方向等)
turtle.home() 返回原点(0,0) - 方向恢复为向右(东方向)

二、画笔设置

函数/方法 说明 参数说明 备注
turtle.pensize(n)turtle.width(n) 设置画笔粗细 n=像素值 默认1
turtle.pencolor(color) 设置画笔颜色 color=颜色名或RGB元组 "red"(255,0,0)(需colormode(255)
turtle.color(p_color, f_color) 同时设置画笔和填充颜色 p_color=画笔颜色,f_color=填充颜色 单参数时统一设置
turtle.fillcolor(color) 设置填充颜色 color=颜色名或RGB值 需配合begin_fill()/end_fill()
turtle.begin_fill() 开始填充 - 在图形绘制前调用
turtle.end_fill() 结束填充 - 闭合图形自动填充
turtle.speed(n) 设置画笔速度 n=0(最快) 或 1(最慢)~10(最快) 0表示无动画

三、画笔运动

函数/方法 说明 参数说明 备注
turtle.forward(d)turtle.fd(d) 向前移动 d=像素距离 方向由当前角度决定
turtle.backward(d)turtle.bk(d) 向后移动 d=像素距离 -
turtle.left(angle)turtle.lt(angle) 左转角度 angle=角度值(度数) 逆时针旋转
turtle.right(angle)turtle.rt(angle) 右转角度 angle=角度值 顺时针旋转
turtle.goto(x, y) 移动到绝对坐标 x=横坐标,y=纵坐标 画线除非penup()
turtle.setheading(angle)turtle.seth(angle) 设置绝对方向 angle=角度(0=东,90=北,180=西,270=南) -
turtle.hideturtle()turtle.ht() 隐藏海龟图标 - 提升绘制速度
turtle.showturtle()turtle.st() 显示海龟图标 - -
turtle.pendown()turtle.down() 落笔(绘制轨迹) - 默认状态
turtle.penup()turtle.up() 抬笔(移动无轨迹) - -

关键注意事项

  1. 坐标系 :画布中心为(0,0),向右为X轴正方向,向上为Y轴正方向。
  2. 颜色模式 :使用RGB值时需先调用 turtle.colormode(255)
  3. 填充规则begin_fill()end_fill()之间的图形需为闭合路径。
  4. 方向系统:角度按标准数学坐标系(0度指向右侧,逆时针增加)。

示例代码(绘制红色五角星)

python 复制代码
import turtle as t

t.setup(600, 400)  # 设置画布大小
t.color("red")      # 画笔和填充色设为红色
t.begin_fill()      # 开始填充
for _ in range(5):  # 绘制五角星
    t.fd(100)
    t.rt(144)
t.end_fill()        # 结束填充
t.hideturtle()      # 隐藏海龟
t.done()            # 结束绘制

掌握这些函数即可实现基础图形绘制!

相关推荐
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程1 天前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪1 天前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook1 天前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田2 天前
使用 pkgutil 实现动态插件系统
python
前端付豪2 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽2 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战2 天前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋2 天前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python