turtle画动态时钟

想写一个动态时钟,自己写了几个都不满意,无意间发现一位大神的文章,学到很多。这么好的贴子不能沉了。
大神文章:https://blog.csdn.net/sin1277839683/article/details/103440544
自己根据参考和理解画的时钟:
在这里插入图片描述
代码如下:

import turtle as t
from datetime import *


# 抬起画笔,向前运动一段距离放下
def skip(step):
    t.penup()
    t.forward(step)
    t.pendown()


def skip_point(x, y):
    t.penup()
    t.goto(x, y)
    t.pendown()


def draw_clock(radius):
    t.reset()  # 清空窗口,重置turtle状态为起始状态
    skip_point(200, 0)
    t.pencolor("yellow")
    t.pensize(80)
    t.circle(200)
    skip_point(0, 0)
    t.pencolor("black")
    t.pensize(7)
    for i in range(60):
        skip(radius)
        if i % 5 == 0:
            t.forward(20)

            if i == 0:
                skip(25)
                t.write(12, align="center", font=("Courier", 14, "bold"))
                skip(-25)
            else:
                skip(25)
                t.write(int(i / 5), align="center", font=("Courier", 14, "bold"))
                skip(-25)
            skip(-radius - 20)
        else:
            skip(5)
            t.dot(6, "green")  # 绘制一个指定直径和颜色的圆点
            skip(-radius-5)
        t.right(6)


def draw_hand(name, length):
    # 注册Turtle形状,建立表针Turtle
    t.reset()
    t.begin_poly()
    t.forward(length)
    # 停止记录多边形的顶点。当前的乌龟位置是多边形的最后一个顶点。将与第一个顶点相连。
    t.end_poly()
    # 返回最后记录的多边形。
    handForm = t.get_poly()
    t.register_shape(name, handForm)


def enabled_clock():
    global secHand, minHand, hurHand
    # 重置Turtle指向北
    t.mode("logo")
    # 建立三个表针Turtle并初始化
    draw_hand("second", 135)
    draw_hand("minute", 120)
    draw_hand("hour", 90)
    secHand = t.Turtle()
    secHand.color("red")
    secHand.shape("second")  # 只能定义成乌龟,不能定义成cat,dog
    minHand = t.Turtle()
    minHand.shape("minute")
    hurHand = t.Turtle()
    hurHand.shape("hour")

    for hand in secHand, minHand, hurHand:
        hand.shapesize(1, 1, 7)
        hand.speed(0)


def action_clock():
    # 绘制表针的动态显示,相当于设立3个turtle对象
    t.hideturtle()
    time = datetime.today()
    second = time.second
    minute = time.minute + second / 60.0
    hour = time.hour + minute / 60.0
    secHand.setheading(6 * second)  # 设置当前朝向为angle角度
    minHand.setheading(6 * minute)
    hurHand.setheading(30 * hour)
    # 100ms后继续调用tick
    t.ontimer(action_clock, 100)


def main():
    # 打开/关闭龟动画,并为更新图纸设置延迟。
    t.tracer(False)
    enabled_clock()
    draw_clock(160)
    t.tracer(True)
    action_clock()
    t.mainloop()


if __name__ == "__main__":
    main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值