[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

运行时的效果示意图如下

最终的效果如下

参考资料

相关推荐
Albert Edison1 小时前
【GUI 自动化测试】Pywinauto 常见操作
自动化测试·python·pywinauto
海兰1 小时前
【高速缓存】RedisVL为文本生成嵌入向量实践指南
人工智能·python·机器学习
2601_955760071 小时前
如何用 Claude Opus 5 API 批量扩展长尾关键词和文章选题
前端·python·搜索引擎
艾斯特_2 小时前
从模型调用到可用聊天应用:会话状态与消息协议
python·ai·aigc
Marst Code2 小时前
Python 3.9 已停止维护!从 3.9 到 3.14 全版本深度对比,生产环境该选哪个?
开发语言·python
llwszx2 小时前
【Java/Go后端手撸原生Agent(第九篇):Plan-and-Execute规划模式——从“走一步看一步“到“先谋后动“】
java·python·golang·agent开发·plan模式·规划执行模式
lxw18449125142 小时前
Python uv 完整使用教程
python·conda·pip·uv
hangyuekejiGEO2 小时前
临沂GEO技术解析与行业应用方案
人工智能·python
不做Java程序猿好多年4 小时前
Java中 String、StringBuffer、StringBuilder 的区别详解
开发语言·python