Python绘制动态指针时钟:代码实现与详解
以下是一个用Python绘制指针会随时间而动的时钟的示例代码:
import turtle
import time
def draw_clock():
# 设置画布大小和背景色
turtle.setup(500, 500)
turtle.bgcolor('black')
turtle.title('Analog Clock')
# 画表盘
turtle.penup()
turtle.goto(0, 200)
turtle.setheading(180)
turtle.color('white')
turtle.pendown()
turtle.circle(200)
# 画时刻度线和数字
for i in range(12):
turtle.penup()
turtle.goto(0, 180)
turtle.setheading(i * 30)
turtle.pendown()
turtle.forward(20)
turtle.penup()
turtle.forward(20)
turtle.write(i+1, align='center', font=('Arial', 12, 'normal'))
# 画指针
turtle.pensize(4)
hour_hand = turtle.Turtle()
minute_hand = turtle.Turtle()
second_hand = turtle.Turtle()
hour_hand.shape('arrow')
hour_hand.shapesize(1, 5)
hour_hand.color('white')
minute_hand.shape('arrow')
minute_hand.shapesize(1, 8)
minute_hand.color('white')
second_hand.shape('arrow')
second_hand.shapesize(1, 10)
second_hand.color('red')
# 循环更新指针位置
while True:
# 获取当前时间
cur_time = time.localtime()
hour = cur_time.tm_hour % 12
minute = cur_time.tm_min
second = cur_time.tm_sec
# 计算指针角度
hour_angle = (hour + minute / 60) * 30
minute_angle = minute * 6
second_angle = second * 6
# 更新指针位置
hour_hand.setheading(hour_angle)
minute_hand.setheading(minute_angle)
second_hand.setheading(second_angle)
# 延时
time.sleep(1)
if __name__ == '__main__':
draw_clock()
代码中使用turtle库绘制时钟的表盘和指针,使用time库获取当前时间并计算指针的角度,然后循环更新指针位置,以实现指针会随时间而动的时钟效果。请注意,代码中的while循环会一直运行,直到程序被手动停止。
原文地址: https://www.cveoy.top/t/topic/nyq5 著作权归作者所有。请勿转载和采集!