借助turtle函数画个钟
时间: 2024-04-04 08:26:05 浏览: 143
以下是使用turtle库绘制钟表的Python代码,其中包括了绘制表盘、时针、分针、秒针以及显示时间的功能。代码中有详细的注释说明每个函数的作用和参数含义。
```python
import turtle
import datetime
# 绘制表盘
def draw_clock(radius):
# 初始化画笔
pen = turtle.Turtle()
pen.speed(0)
pen.pensize(7)
pen.penup()
pen.goto(0, -radius)
pen.pendown()
pen.color("black")
pen.circle(radius)
# 绘制刻度线
for i in range(12):
pen.penup()
pen.goto(0, 0)
pen.setheading(30 * i - 60)
pen.fd(radius - 35)
pen.pendown()
pen.fd(25)
# 绘制数字
for i in range(1, 13):
pen.penup()
pen.goto(0, 0)
pen.setheading(30 * i - 60)
pen.fd(radius - 70)
pen.write(i, align="center", font=("Courier", 14, "bold"))
# 绘制指针
def draw_hand(pen, length, width):
pen.penup()
pen.goto(0, 0)
pen.setheading(90)
pen.pensize(width)
pen.pendown()
pen.fd(length)
# 更新时钟
def update_clock():
# 获取当前时间
now = datetime.datetime.now()
# 绘制时针
hour = now.hour % 12
minute = now.minute
hour_pen = turtle.Turtle()
hour_pen.hideturtle()
hour_pen.speed(0)
hour_pen.color("black")
hour_pen.setheading(30 * hour + minute / 2 - 90)
draw_hand(hour_pen, 60, 7)
# 绘制分针
minute_pen = turtle.Turtle()
minute_pen.hideturtle()
minute_pen.speed(0)
minute_pen.color("black")
minute_pen.setheading(6 * minute - 90)
draw_hand(minute_pen, 100, 5)
# 绘制秒针
second_pen = turtle.Turtle()
second_pen.hideturtle()
second_pen.speed(0)
second_pen.color("red")
second_pen.setheading(6 * now.second - 90)
draw_hand(second_pen, 120, 2)
# 显示时间
time_pen = turtle.Turtle()
time_pen.hideturtle()
time_pen.speed(0)
time_pen.penup()
time_pen.goto(0, 250)
time_pen.write(now.strftime("%Y-%m-%d %H:%M:%S"), align="center", font=("Courier", 14, "bold"))
# 每隔1秒更新一次
turtle.ontimer(update_clock, 1000)
# 设置画布大小和背景色
turtle.setup(600, 600)
turtle.bgcolor("white")
# 绘制表盘
draw_clock(200)
# 更新时钟
update_clock()
# 显示画布
turtle.mainloop()
```
阅读全文