214

今天是情人节,中午当我正苦于给女朋友送什么花的时候,突然想到可以用python绘制一个Digital flower,这样不仅有趣而且有新意,但我是编程小白,于是我将目光转向DeepSeek,了解到了turtle模块,于是也搜索了下使用turtle模块的用法。

turtle模块简介

turtle 模块是 Python 标准库中一个基于 Logo 语言的图形绘制工具,专为编程教育设计。它通过模拟一只”海龟”在画布上移动来绘制图形,turtle是一个可移动的箭头(默认形状),携带画笔属性(颜色、粗细等)。

代码实现

首先初始化设置:

1
2
3
4
5
6
7
setup(600,800,0,0)  # 创建600x800画布
speed(0) # 最快绘制速度
penup() # 提起画笔(移动不绘制)
seth(90) # 画笔方向转为垂直向上
fd(340) # 向上移动340像素(定位到花朵起点)
seth(0) # 方向转回水平向右
pendown() # 落笔开始绘制

绘制玫瑰部分:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
speed(5)      #画笔移动速度为5秒
begin_fill() #开始填充
fillcolor('red') #为红色
circle(50,30) #画一个半径为50,弧度为30的圆

for i in range(10):
fd(1)
left(10) #逆时针转动画笔10度
circle(40,40)

for i in range(6):
fd(1)
left(3)
circle(80,40)

for i in range(20):
fd(0.5)
left(5)
circle(80,45)

for i in range(10):
fd(2)
left(1)
circle(80,25)

for i in range(20):
fd(1)
left(4)
circle(50,50)

time.sleep(0.1)

circle(120,55)

speed(3)

seth(-90)
fd(70)

right(150) #顺时针转动画笔150度
fd(20)

left(140)
circle(140,90)

left(30)
circle(160,100)

left(130)
fd(25)

penup()
right(150)
circle(40,80)
pendown()

left(115)
fd(60)

penup()
left(180)
fd(60)
pendown()

end_fill()

right(120)
circle(-50,50)
circle(-20,90)

speed(1)
fd(75)

speed(1)
circle(90,110)

penup()
left(162)
fd(185)
left(170)
pendown()
circle(200,10)
circle(100,40)
circle(-52,115)
left(20)

绘制花枝:
1
2
3
4
circle(100,20)
circle(300,20)
speed(1)
fd(250)

绘制绿色叶子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
penup()
speed(2)
left(180)
fd(250)
circle(-300,7)
right(80)
circle(200,5)
pendown()

left(60)
begin_fill()
fillcolor('green')
circle(-80,100)
right(90)
fd(10)
left(20)
circle(-63,127)
end_fill()

penup()
left(50)
fd(20)
left(180)

pendown()
circle(200,25)


右:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
penup()
fd(180)

right(40)
pendown()
begin_fill()
fillcolor('green')
circle(-100,80)
right(150)
fd(10)
left(60)
circle(-80,98)
end_fill()

penup()
left(60)
fd(13)
left(180)

pendown()
speed(1)
circle(-200,23)

添加文字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
penup()
goto(-140, -320) # 调整文字起始位置
pendown()
color("#FF0066") # 使用玫瑰同色系

# 设置手写字体风格(需要系统有该字体,若无可用"Script"替代)
font_style = ("Segoe Script", 24, "italic")

# 逐个字母绘制实现手写效果
def hand_write(text, delay=0.2):
penup()
for char in text:
write(char, move=True, font=font_style)
time.sleep(delay) # 模拟逐字书写效果

# 设置画笔特性
pensize(2)
tilt(15) # 笔尖倾斜15度

# 绘制姓名
hand_write("I love U")
penup()
goto(160, -370) # 调整文字起始位置
pendown()
color("silver")
hand_write("20250214")

最终效果如下:

参考资料

Author

LLLLAAAA

Posted on

2025-02-14

Updated on

2025-02-20

Licensed under

Comments