[Python] 用 turtle 来绘制瑞典国旗

背景

turtle --- Turtle graphics 中提供了关于 turtle\text{turtle} turtle 模块的介绍。我想用 turtle\text{turtle} turtle 来生成些简单的图案,以巩固学习的效果。有些国家的国旗图案比较简单,可以从这里入手

正文

基本的数据

根据 Sweden 网页所提供的信息,瑞典国旗中各部分的比例如下图所示

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

代码

我的整体思路是这样的 ⬇️

  1. 先画出一个蓝色的矩形
  2. 画出黄色十字的那一横
  3. 画出黄色十字的那一竖

在此基础上,可以写出完整的 Python\text{Python} 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\text{Python} Python 程序保存为 draw_sweden_national_flag.py\text{draw\_sweden\_national\_flag.py} draw_sweden_national_flag.py。使用如下命令可以运行 draw_sweden_national_flag.py\text{draw\_sweden\_national\_flag.py} draw_sweden_national_flag.py

bash 复制代码
python3 draw_sweden_national_flag.py

运行时的效果示意图如下

最终的效果如下

参考资料

相关推荐
白山编程大哥1 小时前
Java 集合算法:从排序、查找到底层原理的实战指南
java·python·算法
昭昭日月明2 小时前
RAGFlow 入门,不用从零造轮子
python·ai编程
莓有烦恼吖3 小时前
Vibe Coding 的一些思考
python
小白学大数据3 小时前
超简单:用 Python 让 Excel 飞起来:用 openpyxl 把重复报表整理交给脚本
开发语言·数据库·python·excel
爱丶不疚3 小时前
写给前端工程师的现代 Python 工程化最佳实践:从 pnpm 到 uv,从 CommonJS 到 src-layout
javascript·python·typescript
2601_962297254 小时前
C# vs Java vs Python:YOLO工业部署性能对比实战
java·python·c·工业视觉·性能对比
CTA终结者4 小时前
示例、拆解和练习,要连成一条量化补课线
人工智能·python
lolijiaqi154 小时前
一线观察:长期体验后发现的医疗器械 CDMO 底层现象
大数据·python
spencer_tseng4 小时前
[j2cache ehcache.xml]/tmp/.ehcache-diskstore.lock (Permission denied)
xml·linux·python·ehcache·[j2cache
梦想不只是梦与想5 小时前
Python Web 框架:FastAPI
python·fastapi·web框架