import tkinter as tk
import math
from datetime import datetime

# 主窗口
root = tk.Tk()
root.title("Python 时钟")
root.geometry("420x520")
root.resizable(False, False)

# 画布绘制表盘
canvas = tk.Canvas(root, width=400, height=400, bg="#f8f8f8")
canvas.pack(pady=10)

# 数字时间标签
time_label = tk.Label(root, text="00:00:00", font=("Consolas", 32))
time_label.pack()

center_x = 200
center_y = 200
radius = 180

# 画表盘外圈
canvas.create_oval(center_x-radius, center_y-radius, center_x+radius, center_y+radius, width=3)

# 绘制12个刻度数字
for i in range(12):
    angle = math.radians(i * 30 - 90)
    x = center_x + (radius - 25) * math.cos(angle)
    y = center_y + (radius - 25) * math.sin(angle)
    canvas.create_text(x, y, text=str(i+1), font=("Arial",18))

# 保存指针id，方便后续删除重绘
hour_hand = None
min_hand = None
sec_hand = None

def update_clock():
    global hour_hand, min_hand, sec_hand
    now = datetime.now()
    h = now.hour % 12
    m = now.minute
    s = now.second

    # 更新数字时间
    time_str = f"{now.hour:02d}:{m:02d}:{s:02d}"
    time_label.config(text=time_str)

    # 删除旧指针
    if hour_hand:
        canvas.delete(hour_hand)
    if min_hand:
        canvas.delete(min_hand)
    if sec_hand:
        canvas.delete(sec_hand)

    # 角度计算：-90度是因为0角度朝右，我们需要12点朝上
    hour_angle = math.radians(h * 30 + m * 0.5 - 90)
    min_angle = math.radians(m * 6 - 90)
    sec_angle = math.radians(s * 6 - 90)

    # 指针长度
    h_len = radius * 0.55
    m_len = radius * 0.75
    s_len = radius * 0.85

    # 绘制时针
    hx = center_x + h_len * math.cos(hour_angle)
    hy = center_y + h_len * math.sin(hour_angle)
    hour_hand = canvas.create_line(center_x, center_y, hx, hy, width=6, fill="#222222")

    # 绘制分针
    mx = center_x + m_len * math.cos(min_angle)
    my = center_y + m_len * math.sin(min_angle)
    min_hand = canvas.create_line(center_x, center_y, mx, my, width=3, fill="#333333")

    # 绘制秒针
    sx = center_x + s_len * math.cos(sec_angle)
    sy = center_y + s_len * math.sin(sec_angle)
    sec_hand = canvas.create_line(center_x, center_y, sx, sy, width=2, fill="#dd2222")

    # 中心点小圆
    canvas.create_oval(center_x-5, center_y-5, center_x+5, center_y+5, fill="black")

    # 100ms刷新一次
    root.after(100, update_clock)

# 启动时钟刷新
update_clock()

root.mainloop()
