背景
turtle --- Turtle graphics 中提供了关于 turtle 模块的介绍。我想用 turtle 来生成些简单的图案,以巩固学习的效果。有些国家的国旗图案比较简单,可以从这里入手
正文
基本的数据
根据 Sweden 网页所提供的信息,瑞典国旗中各部分的比例如下图所示

我在别的网站上搜到了瑞典国旗中,蓝色和黄色的具体数值(下图中给出了两组数值,我们就用 NCS 那一组吧)。

代码
我的整体思路是这样的 ⬇️
- 先画出一个蓝色的矩形
- 画出黄色十字的那一横
- 画出黄色十字的那一竖
在此基础上,可以写出完整的 Python 代码 ⬇️
python
import turtle
ratio = 40
length = 5 + 2 + 9
height = 4 + 2 + 4
def draw_rectangle(start_x, start_y, length, height, color):
turtle.teleport(start_x, start_y)
turtle.setheading(0)
turtle.color(color, color)
with turtle.fill():
turtle.forward(length)
turtle.right(90)
turtle.forward(height)
turtle.right(90)
turtle.forward(length)
turtle.right(90)
turtle.forward(height)
draw_rectangle(-length * ratio // 2, height * ratio // 2, length * ratio, height * ratio, "#005583")
draw_rectangle(-length * ratio // 2, 2 * ratio // 2, length * ratio, 2 * ratio, "#FFC200")
draw_rectangle(-length * ratio // 2 + 5 * ratio, height * ratio // 2, 2 * ratio, height * ratio, "#FFC200")
turtle.hideturtle()
turtle.mainloop()
请将以上 Python 程序保存为 draw_sweden_national_flag.py。使用如下命令可以运行 draw_sweden_national_flag.py
bash
python3 draw_sweden_national_flag.py
运行时的效果示意图如下

最终的效果如下
