Kodewick
开始学 →

Python 画时钟

表盘只画一次,指针每秒擦掉重画一次,跟着你电脑上的时间走。

Python 画时钟
完整代码(60 行)
import turtle
import datetime

screen = turtle.Screen()
screen.bgcolor("#eef2f5")
screen.tracer(0)
face = turtle.Turtle()
face.hideturtle()
face.penup()

# 表盘
face.goto(0, 0)
face.dot(400, "#2b2d42")
face.dot(370, "white")
# 刻度:60 个,整点的长一点粗一点
for i in range(60):
    face.goto(0, 0)
    face.setheading(90 - i * 6)
    face.forward(170)
    face.pendown()
    face.pensize(5 if i % 5 == 0 else 2)
    face.forward(-18 if i % 5 == 0 else -8)
    face.penup()
# 数字
for h in range(1, 13):
    face.goto(0, 0)
    face.setheading(90 - h * 30)
    face.forward(130)
    face.sety(face.ycor() - 12)
    face.write(str(h), align="center", font=("Arial", 20, "bold"))

hands = turtle.Turtle()
hands.hideturtle()


def hand(angle, length, width, color):
    hands.penup()
    hands.goto(0, 0)
    hands.setheading(90 - angle)
    hands.pendown()
    hands.pencolor(color)
    hands.pensize(width)
    hands.forward(length)


def tick():
    now = datetime.datetime.now()
    hands.clear()
    hand((now.hour % 12 + now.minute / 60) * 30, 90, 9, "#2b2d42")
    hand((now.minute + now.second / 60) * 6, 135, 6, "#2b2d42")
    hand(now.second * 6, 155, 2, "#ef233c")
    hands.penup()
    hands.goto(0, 0)
    hands.dot(16, "#ef233c")
    screen.update()
    screen.ontimer(tick, 1000)


tick()
turtle.done()

怎么画的

两只海龟:face 画表盘、刻度和数字,只画一次;hands 画指针,每秒 hands.clear() 擦掉重画。

钟表从 12 点开始顺时针走,turtle 的 0 度朝右、逆时针为正,所以方向是 90 - 角度。秒针每秒 6 度,分针每分钟 6 度,时针每小时 30 度。

datetime.datetime.now() 取现在的时间;时针还要加上 minute / 60,到 3 点半时针才会在 3 和 4 中间。

screen.ontimer(tick, 1000) 一秒后再调用 tick,钟就走起来了。

常见问题

这一页上钟会一直走吗?

这一页上动画放 30 秒后停住;在自己电脑上运行会一直走,关窗口才停。

为什么指针要用另一只海龟?

clear() 只擦掉这只海龟自己画的。指针单独一只海龟,擦指针时表盘不会被擦掉。

换个样子