python海龟绘制平滑时钟

运行效果

image

代码

import turtle as t
import time as tm

def DrawDial(): # 绘制表盘
    ts = t.Turtle()
    ts.hideturtle()
    ts.pensize(20)
    ts.speed(0)
    ts.color("cyan","yellow")
    ts.penup()
    ts.goto(0,-200)
    ts.pendown()
    ts.begin_fill()
    ts.circle(200)
    ts.end_fill()
    ts.penup()
    ts.home()
    ts.pensize(5)
    ts.pencolor("blue")
    for i in range(12):
        ts.setheading(i * 30)
        if (i % 3 == 0):
            ts.forward(180)
            ts.pendown()
            ts.forward(20)
            ts.penup()
            ts.home()
        else:
            ts.forward(190)
            ts.pendown()
            ts.forward(10)
            ts.penup()
            ts.home()            
            

t.tracer(0) # 停止自动更新画面
DrawDial()

t_s = t.Turtle() # 定义一个绘制秒针的海龟
t_s.color("red")
t_s.pensize(2)
t_s.speed(0)
t_s.hideturtle()

t_m = t.Turtle() # 定义一个分针的海龟
t_m.color("blue")
t_m.pensize(4)
t_m.speed(0)
t_m.hideturtle()

t_h = t.Turtle() # 定义一个时针的海龟
t_h.color("black")
t_h.pensize(6)
t_h.speed(0)
t_h.hideturtle()

time_zone = 8 # 定义时区,中国是+8

while True:
    # 从1970-01-01 00:00:00 UTC,格林威治时间
    # 开始到现在所经历的时间,以浮点数的'秒'来表示
    # 乘以1000得到毫秒数
    ms = int(tm.time() * 1000)
    # 60000 一分钟的毫秒数
    t_s.setheading(-(ms % 60000) * 360 / 60000 + 90)
    t_s.forward(190)
    t_s.dot(10)
    # 3600000 一小时的毫秒数
    t_m.setheading(-(ms % 3600000) * 360 / 3600000 + 90)
    t_m.forward(170)
    t_m.dot(12)
    # 显示小时的时候 -240度 是因为中国是东8区
    # 43200000 12小时的毫秒数
    t_h.setheading(-(ms % 43200000) * 360 / 43200000 + 90 - time_zone * 30)
    t_h.forward(140)
    t_h.dot(14)
    t.update() # 手动绘制
    tm.sleep(0.001)
    t_s.undo()
    t_s.undo()
    t_m.undo()
    t_m.undo()
    t_h.undo()
    t_h.undo()
    

posted @ 2024-02-02 18:41  iamy  阅读(72)  评论(0)    收藏  举报