当前位置:首页>python>python怎么学不枯燥,用python自带的画图库——用python画一朵樱花树,效果还不错

python怎么学不枯燥,用python自带的画图库——用python画一朵樱花树,效果还不错

  • 2026-10-11 07:21:12
python怎么学不枯燥,用python自带的画图库——用python画一朵樱花树,效果还不错

运行效果

整体思路

绘制树枝:使用函数递归实现,从主干到分叉、树枝。

画花瓣:在树枝末端位置绘制,使用函数实现。

画树枝

使用递归函数实现树枝不断分叉,每一层分叉,树枝会变短、变细。

函数参数:树枝长度、旋转度数、画笔粗细。

import turtleimport randomturtle.screensize(800,600,"#fafafa")turtle.tracer(0)  # 关闭绘制过程,直接出结果t = turtle.Turtle()#产生画笔t.hideturtle()t.speed(0)branch_tips = []def draw_branch(branch_len, angle, width):    if branch_len < 5:          # 枝条太短就不画了,递归终止条件        branch_tips.append(t.pos())  # 记录末端位置        return    t.pensize(width)            # width决定了树枝粗细    t.pencolor("#8B4513")       # 树枝为棕色,数值可换,网上搜索16进制颜色    t.forward(branch_len)       # 前进一段距离    # 右边分叉,右分叉的长度每次变为前一次的0.6~0.8倍之间。    t.right(angle)    draw_branch(branch_len * random.uniform(0.6, 0.8),                 angle, width * 0.7)    # 左边分叉,注意旋转度数    t.left(angle * 2)    draw_branch(branch_len * random.uniform(0.6, 0.8),                 angle, width * 0.7)    # 回到原位    t.right(angle)    t.backward(branch_len)

调用函数,会产生一颗光秃秃的树

t.left(90)              # 让海龟朝上(默认朝右)t.penup()t.goto(0, -260)        # 从底部中间开始t.pendown()draw_branch(100, 25, 12) # 初始长度100,角度25度,笔宽12

末端画花

使用函数实现绘制一朵花,每朵花有5个花瓣,颜色从列表中随机抽取。

def draw_flower(x, y, size):    """在 (x, y) 处画一朵5瓣的花朵"""    colors = ["#FFB7C5", "#FF9AAF", "#FFC0CB", "#FFD1DC",              "#FFA6C9"]    color = random.choice(colors) # 随机抽出一种颜色作为花瓣颜色    for i in range(5):              # 5个花瓣        t.penup()        t.goto(x, y)        t.setheading(i * 72)       # 每瓣间隔72度(360/5)        t.pendown()        t.color(color)        t.begin_fill()        t.circle(size, 60)               # 画弧线        t.left(120)        t.circle(size, 60)               # 再画一段弧线        t.end_fill()                    #两条弧线组成花瓣     # 金色花心    t.penup()    t.goto(x, y - size * 0.3)    t.pendown()    t.color("#FFD700")    t.begin_fill()    t.circle(size * 0.25)    t.end_fill()

调用画花函数

"""在每个树枝末端附近画几朵花,使用循环实现"""for tip in branch_tips:    count = random.randint(2, 4)      # 每个末端2~4朵    for _ in range(count):        px = tip[0] + random.uniform(-20, 20)        py = tip[1] + random.uniform(-10, 25)        draw_flower(px, py, random.uniform(6, 12))

一棵樱花树成功了,你可以调整樱花树中绘制树的树枝长度、角度、树枝粗细参数,使樱花树的样子发生改变,快点去试试吧!(绘制出来需要一点时间,耐心等待一下。)

END

最新文章

随机文章