[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

运行时的效果示意图如下

最终的效果如下

参考资料

相关推荐
Wzx19801222 分钟前
Python Agent 短期记忆设计:从对话历史到 LangGraph Checkpointer
开发语言·python
ljt272496066130 分钟前
Python笔记(五)--读写文件
笔记·python
破茧蝴蝶9 小时前
Python分布式爬虫完整教程
开发语言·python
benchmark_cc9 小时前
量化系统架构设计:为什么应该将数据获取与策略逻辑解耦?
python·数据分析·pandas·量化交易·股票数据·quantdash
凤山老林9 小时前
Spring Boot 启动冲刺:耗时剖析、懒加载策略与事件驱动初始化优化
spring boot·后端·python
小白快快跑哦10 小时前
python-字符串全解(六):正则表达式-逻辑运算或
python·正则表达式·字符串·逻辑运算
Thinker QAQ10 小时前
并发编程(九):BlockingQueue 与 Channel——语言层的原子性、可见性与有序性
java·python·go·并发编程·channel·blockingqueue·message passing
道满科技10 小时前
Function Calling 参数总出错?只修参数就行
linux·windows·python
霸道流氓气质11 小时前
RAG 可观测性与生产监控实战:四层遥测模型、五大仪表盘与 OpenTelemetry 全链路追踪的 Java 生产级实现
java·人工智能·python