Python
构建Desktop Time Clock【支持秒显示】
起因
由于部分电脑只能显示时间的时分,不支持显示秒,利用Python
的tkinter
库做了一个桌面时钟,该时钟能够获取系统实时时钟,并精确到秒显示
附注:本程序每1s
才会更新一次时间变量,所占用系统资源极少,可长时间运行
设置自启动
- 创建 DesktopTimeClock.bat 文件,文件里写入如下内容:
1.1 假设你的文件存放在C:\\Desktop\\DesktopTimeClock.py
1.2 以下文件路劲和文件名需要根据个人实际情况进行替换
cd C:\\Desktop
python DesktopTimeClock.py
运行DesktopTimeClock.bat: 双击运行 DesktopTimeClock.bat 文件,桌面时钟将会出现在您的屏幕上。
创建快捷方式:右键点击 DesktopTimeClock.bat 文件,选择“创建快捷方式”。
添加到启动文件夹: 将快捷方式移动到启动文件夹(
C:\Users<用户名>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
)中。完成: 现在,每次启动电脑时,桌面时钟都会自动显示。
关闭程序: 点击桌面时钟窗口,并按住
Esc
键1s
即可关闭程序。
代码实现
- 时钟的位置和字体大小可根据个人需要自行调节
from tkinter import *
import time, datetime
from time import gmtime, strftime
root = Tk()
# Window Attributes
root.overrideredirect(1) # 隐藏窗口边框
root.wm_attributes("-transparentcolor", "gray99") # 设置透明背景色
running = True # 运行状态
# 关闭窗口函数
def close(event):
global running
running = False
root.bind('<Escape>', close) # 绑定Esc键关闭窗口
screen_width = root.winfo_screenwidth() # 获取屏幕宽度
screen_height = root.winfo_screenheight() # 获取屏幕高度
timeframe = Frame(root, width=screen_width, height=screen_height, bg="gray99") # 创建主框架
timeframe.grid(row=0,column=0)
tkintertime = StringVar() # 创建时间变量
timelabel = Label(timeframe, textvariable=tkintertime, fg="white", bg="gray99", font=("NovaMono", 40)) # 创建时间标签
# timelabel.place(y=screen_height/2 - 30, x=screen_width/2, anchor="center") # 设置时间标签位置(屏幕中心)
timelabel.place(y=screen_height/4 - 30, x=screen_width-screen_width/4, anchor="center") # 设置时间标签位置(右上角)
tkinterdate = StringVar() # 创建日期变量
datelabel = Label(timeframe, textvariable=tkinterdate, fg="white", bg="gray99", font=("Bahnschrift", 15)) # 创建日期标签
# datelabel.place(y=screen_height/2 + 30, x=screen_width/2, anchor="center") # 设置日期标签位置(屏幕中心)
datelabel.place(y=screen_height/4 + 30, x=screen_width-screen_width/4, anchor="center") # 设置日期标签位置(右上角)
while running:
tkintertime.set(value=strftime("%H:%M:%S")) # 更新时间
tkinterdate.set(value=strftime("%A, %e %B")) # 更新日期
root.update_idletasks() # 更新窗口
root.update() # 更新窗口
time.sleep(1) # 延迟1秒