AI学习第五天-python的基础使用-趣味图形

一、Turtle 基础命令速查表

命令 功能 示例
forward(distance) 向前移动指定距离 turtle.forward(100)
backward(distance) 向后移动指定距离 turtle.backward(50)
left(angle) 左转指定角度 turtle.left(90)
right(angle) 右转指定角度 turtle.right(45)
goto(x, y) 移动到坐标 (x,y) turtle.goto(0, 0)
circle(radius) 绘制半径为 radius 的圆 turtle.circle(30)
penup() 抬起画笔(不绘制) turtle.penup()
pendown() 放下画笔(开始绘制) turtle.pendown()
pensize(size) 设置画笔粗细 turtle.pensize(3)
pencolor(color) 设置画笔颜色 turtle.pencolor("red")
fillcolor(color) 设置填充颜色 turtle.fillcolor("blue")
begin_fill() 开始填充形状 turtle.begin_fill()
end_fill() 结束填充形状 turtle.end_fill()
speed(speed) 设置绘图速度(0-10) turtle.speed(5)
done() 保持窗口不关闭 turtle.done()

二、绘图流程模板

收起

python

复制代码
import turtle

# 初始化画布
turtle.setup(width=600, height=400)  # 设置画布大小
turtle.title("Turtle Demo")  # 设置窗口标题

# 创建海龟对象
t = turtle.Turtle()  # 也可以直接使用turtle函数

# 绘图代码
t.forward(100)
t.left(90)
t.forward(100)

# 保持窗口
turtle.done()

三、基础案例

案例 1:绘制正方形

收起

python

复制代码
import turtle

t = turtle.Turtle()
for _ in range(4):
    t.forward(100)
    t.left(90)
turtle.done()
案例 2:绘制圆形

收起

python

复制代码
import turtle

t = turtle.Turtle()
t.circle(50)  # 半径50
turtle.done()
案例 3:绘制三角形

注意:转动的角度是外角

收起

python

复制代码
import turtle

t = turtle.Turtle()
for _ in range(3):
    t.forward(120)
    t.left(120)
turtle.done()
案例 4:绘制螺旋线

收起

python

复制代码
import turtle

t = turtle.Turtle()
length = 10
angle = 89

for _ in range(50):
    t.forward(length)
    t.left(angle)
    length += 2  # 逐渐增加长度
turtle.done()

四、进阶案例

案例 5:绘制花朵

收起

python

复制代码
import turtle
import random

t = turtle.Turtle()
t.speed(0)
colors = ["red", "orange", "yellow", "green", "blue"]

for _ in range(36):
    t.color(random.choice(colors))
    t.circle(100)
    t.left(10)
turtle.done()
案例 6:绘制五角星

收起

python

复制代码
import turtle

t = turtle.Turtle()
t.color("red")
t.begin_fill()

for _ in range(5):
    t.forward(150)
    t.left(144)  # 内角计算:180 - 360/(2*5) = 144

t.end_fill()
turtle.done()

五、注意事项

  1. 坐标系:画布中心为 (0,0),向右为 x 轴正方向,向上为 y 轴正方向。
  2. 角度单位:默认以度数为单位(如左转 90 度)。
  3. 颜色设置:支持颜色名称(如 "red")或 RGB 值(如 (255, 0, 0))。
  4. 循环优化:复杂图形建议用循环减少重复代码。
相关推荐
B站计算机毕业设计之家10 小时前
智慧交通项目:Python+YOLOv8 实时交通标志系统 深度学习实战(TT100K+PySide6 源码+文档)✅
人工智能·python·深度学习·yolo·计算机视觉·智慧交通·交通标志
IT森林里的程序猿10 小时前
基于机器学习方法的网球比赛胜负趋势预测
python·机器学习·django
正牌强哥10 小时前
Futures_ML——机器学习在期货量化交易中的应用与实践
人工智能·python·机器学习·ai·交易·akshare
倔强青铜三11 小时前
苦练Python第62天:零基础玩转CSV文件读写,csv模块实战
人工智能·python·面试
郝学胜-神的一滴11 小时前
Effective Python 第43条:自定义容器类型为什么应该从 `collections.abc` 继承?
开发语言·python
银行数字化转型导师坚鹏11 小时前
如何设计优秀的企业微信私域运营实战培训方案
大数据·python·企业微信
jerryinwuhan12 小时前
最短路径问题总结
开发语言·人工智能·python
shelter -唯12 小时前
京东手机项目:手机受欢迎的影响因素分析
python·机器学习·智能手机
kobe_OKOK_12 小时前
Django ORM 字段查询表达式(Field lookup expressions)
后端·python·django
C嘎嘎嵌入式开发12 小时前
(1)100天python从入门到拿捏
开发语言·python