Skip to content

海龟绘图-数字时钟

难度:⭐⭐⭐⭐

1. 题目描述

题目描述

使用海龟绘图 turtle 绘制 LED 数字时钟

2. 关键点

  • 海龟绘图,绘制数字

3. 代码实现

点击显示代码
python
import datetime
import time
import turtle


# 每个数字对应的笔画,设定数字左边中间坐标为(0, 0)
number_pen = {
    0: [(0, 1), (0, 0), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1)],
    1: [(1, 1), (1, 0), (1, -1)],
    2: [(0, 1), (1, 1), (1, 0), (0, 0), (0, -1), (1, -1)],
    3: [(0, 1), (1, 1), (1, 0), (0, 0), (1, 0), (1, -1), (0, -1)],
    4: [(0, 1), (0, 0), (1, 0), (1, 1), (1, 0), (1, -1)],
    5: [(1, 1), (0, 1), (0, 0), (1, 0), (1, -1), (0, -1)],
    6: [(1, 1), (0, 1), (0, 0), (0, -1), (1, -1), (1, 0), (0, 0)],
    7: [(0, 1), (1, 1), (1, 0), (1, -1)],
    8: [(1, 1), (0, 1), (0, 0), (1, 0), (1, -1), (0, -1), (0, 0), (1, 0), (1, 1)],
    9: [(1, 1), (0, 1), (0, 0), (1, 0), (1, 1), (1, 0), (1, -1), (0, -1)],
}


def draw_number(number, pos=(0, 0)):
    """绘画数字"""
    number_len = 50  # 笔画长度
    for i, (x, y) in enumerate(number_pen[number]):
        x *= number_len
        y *= number_len
        x += pos[0]
        y += pos[1]
        if i == 0:  # 每个数字初始的时候需要设置初始位置
            turtle.hideturtle()
            turtle.penup()
            turtle.setpos(x, y)
            turtle.pendown()
            turtle.showturtle()
        turtle.setpos(x, y)


def clock():
    """绘制时钟"""
    while True:
        now = datetime.datetime.now().strftime('%H%M%S')
        for i, num in enumerate(now):
            num = int(num)
            draw_number(num, ((i-3) * 100, 0))
        time.sleep(1)
        turtle.reset()


clock()

4. 运行示例

5. 进阶思考

  1. 只重新绘制变动的数字
  2. 添加背景、颜色等,做出精美的数字时钟