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

发布于:2025-05-20 ⋅ 阅读:(21) ⋅ 点赞:(0)

以下是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度指向右侧,逆时针增加)。

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

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()            # 结束绘制

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


网站公告

今日签到

点亮在社区的每一天
去签到