以下是一个使用 Python 的 turtle 库绘制动态时钟的代码。

import turtle
import time

# 设置 turtle 画布
window = turtle.Screen()
window.bgcolor('black')
window.setup(width=600, height=600)
window.title('Clock')

# 画时钟外形
clock_pen = turtle.Turtle()
clock_pen.hideturtle()
clock_pen.speed(0)
clock_pen.pensize(4)
clock_pen.color('white')
clock_pen.penup()
clock_pen.goto(0, 200)
clock_pen.setheading(180)
clock_pen.pendown()
clock_pen.circle(200)
clock_pen.penup()
clock_pen.goto(0, 0)
clock_pen.pendown()
clock_pen.dot(10)

# 画时钟刻度
for i in range(12):
    clock_pen.penup()
    clock_pen.goto(0, 180)
    clock_pen.setheading(30 * i)
    clock_pen.pendown()
    clock_pen.forward(20)
    clock_pen.penup()
    clock_pen.goto(0, 0)
    clock_pen.right(30)

# 画时针、分针和秒针
hour_pen = turtle.Turtle()
hour_pen.hideturtle()
hour_pen.speed(0)
hour_pen.pensize(6)
hour_pen.color('white')
minute_pen = hour_pen.clone()
minute_pen.pensize(4)
minute_pen.color('yellow')
second_pen = hour_pen.clone()
second_pen.pensize(2)
second_pen.color('red')

while True:
    # 获取当前时间
hour = int(time.strftime('%I'))
    minute = int(time.strftime('%M'))
    second = int(time.strftime('%S'))

    # 计算时针、分针、秒针的角度
hour_angle = (hour / 12) * 360 + (minute / 60) * 30
    minute_angle = (minute / 60) * 360
    second_angle = (second / 60) * 360

    # 绘制时针、分针、秒针
hour_pen.penup()
hour_pen.goto(0, 0)
hour_pen.setheading(90)
hour_pen.right(hour_angle)
hour_pen.pendown()
hour_pen.forward(80)

    minute_pen.penup()
    minute_pen.goto(0, 0)
    minute_pen.setheading(90)
    minute_pen.right(minute_angle)
    minute_pen.pendown()
    minute_pen.forward(120)

    second_pen.penup()
    second_pen.goto(0, 0)
    second_pen.setheading(90)
    second_pen.right(second_angle)
    second_pen.pendown()
    second_pen.forward(150)

    # 每隔1秒更新一次
    time.sleep(1)

    # 清除时针、分针、秒针
hour_pen.clear()
    minute_pen.clear()
    second_pen.clear()

# 关闭窗口
window.mainloop()

该代码使用 time 库获取当前时间,并通过计算角度来绘制时针、分针和秒针。时针的角度由小时和分钟共同决定,分针和秒针的角度分别由分钟和秒钟决定。每隔 1 秒钟更新一次,清除之前绘制的指针,重新绘制新的指针。


原文地址: https://www.cveoy.top/t/topic/nyqE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录