> 技术文档 > Python 写的《桌面时钟》屏保_电脑桌面时钟代码

Python 写的《桌面时钟》屏保_电脑桌面时钟代码

原代码:

# 日历式时钟# 导入所需的库# 作者:Hoye# 日期:2024年12月16日# 功能:显示当前日期、星期、时间,并显示模拟时钟import tkinter as tkfrom tkinter import ttkimport timeimport mathimport sysdef exit_screensaver(event=None): root.quit()def draw_clock_face(): # 清除画布 clock_canvas.delete(\"all\") # 获取当前时间 current_time = time.localtime() hours = current_time.tm_hour % 12 minutes = current_time.tm_min seconds = current_time.tm_sec # 时钟外圈 clock_canvas.create_oval(10, 10, 390, 390, width=2, outline=\"#ECF0F1\") # 绘制刻度和数字 for i in range(12): angle = i * math.pi/6 - math.pi/2 # 刻度线 start_x = 200 + 190 * math.cos(angle) start_y = 200 + 190 * math.sin(angle) end_x = 200 + 180 * math.cos(angle) end_y = 200 + 180 * math.sin(angle) width = 3 if i % 3 == 0 else 1 clock_canvas.create_line(start_x, start_y, end_x, end_y, fill=\"#ECF0F1\", width=width) # 添加数字 num = 12 if i == 0 else i text_x = 200 + 155 * math.cos(angle) text_y = 200 + 155 * math.sin(angle) clock_canvas.create_text(text_x, text_y, text=str(num), font=(\"Microsoft YaHei UI\", 20, \"bold\"), fill=\"#ECF0F1\") # 时针 hour_angle = (hours + minutes/60) * math.pi/6 - math.pi/2 hour_x = 200 + 100 * math.cos(hour_angle) hour_y = 200 + 100 * math.sin(hour_angle) clock_canvas.create_line(200, 200, hour_x, hour_y, fill=\"#3498DB\", width=8) # 分针 min_angle = minutes * math.pi/30 - math.pi/2 min_x = 200 + 140 * math.cos(min_angle) min_y = 200 + 140 * math.sin(min_angle) clock_canvas.create_line(200, 200, min_x, min_y, fill=\"#ECF0F1\", width=6) # 秒针 sec_angle = seconds * math.pi/30 - math.pi/2 sec_x = 200 + 160 * math.cos(sec_angle) sec_y = 200 + 160 * math.sin(sec_angle) clock_canvas.create_line(200, 200, sec_x, sec_y, fill=\"#BDC3C7\", width=2) # 中心点 clock_canvas.create_oval(195, 195, 205, 205, fill=\"#3498DB\") # 每秒更新 root.after(1000, draw_clock_face)def update_clock(): current_time = time.localtime() year = current_time.tm_year month = current_time.tm_mon day = current_time.tm_mday weekday = current_time.tm_wday hours = current_time.tm_hour minutes = current_time.tm_min seconds = current_time.tm_sec date_str = f\"{year}年{month:02d}月{day:02d}日\" weekday_str = [\"星期一\", \"星期二\", \"星期三\", \"星期四\", \"星期五\", \"星期六\", \"星期日