python写一个时钟表
时间: 2023-12-12 17:07:16 浏览: 103
抱歉,我是AI语言模型,无法进行图形界面的编程。但我可以提供一些思路和代码片段供您参考:
思路:
1.使用tkinter模块创建窗口
2.使用canvas创建一个圆形表盘
3.在表盘上绘制刻度和数字
4.在表盘中央绘制指针
5.使用time模块获取当前时间,并将指针旋转到对应的位置
代码片段:
import tkinter as tk
import time
import math
root = tk.Tk()
root.title("时钟表")
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
# 创建表盘
canvas.create_oval(50, 50, 350, 350, width=2)
# 绘制刻度和数字
for i in range(12):
x1 = 200 + 150 * math.cos(math.pi / 6 * i - math.pi / 2)
y1 = 200 + 150 * math.sin(math.pi / 6 * i - math.pi / 2)
x2 = 200 + 130 * math.cos(math.pi / 6 * i - math.pi / 2)
y2 = 200 + 130 * math.sin(math.pi / 6 * i - math.pi / 2)
canvas.create_line(x1, y1, x2, y2, width=2)
canvas.create_text(x1, y1, text=str(i+1), font=("Arial", 12))
# 创建指针
hour_hand = canvas.create_line(200, 200, 200, 150, width=4)
minute_hand = canvas.create_line(200, 200, 200, 100, width=2)
second_hand = canvas.create_line(200, 200, 200, 80, width=1)
def update():
# 获取当前时间
now = time.localtime()
hour = now.tm_hour % 12
minute = now.tm_min
second = now.tm_sec
# 计算指针旋转的角度
hour_angle = (hour + minute / 60) * 30 - 90
minute_angle = minute * 6 - 90
second_angle = second * 6 - 90
# 旋转指针
canvas.coords(hour_hand, 200, 200, 200 + 60 * math.cos(math.radians(hour_angle)),
200 + 60 * math.sin(math.radians(hour_angle)))
canvas.coords(minute_hand, 200, 200, 200 + 90 * math.cos(math.radians(minute_angle)),
200 + 90 * math.sin(math.radians(minute_angle)))
canvas.coords(second_hand, 200, 200, 200 + 100 * math.cos(math.radians(second_angle)),
200 + 100 * math.sin(math.radians(second_angle)))
# 循环调用更新函数
root.after(1000, update)
update()
root.mainloop()
阅读全文