全屏电子时钟,接下来,我将用Python tkinter库实现全屏电子时钟。如有问题,望多多指正。
1.导入所需的库
本章,需要导入tkinter,time等模块,代码如下:
import tkinter as tk
import time
2.科技蓝界面开发与日期显示
(1)科技蓝界面制作
root = tk.Tk()
root.title("时间")
root.attributes('-fullscreen', True)
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
root.geometry(f'{screen_width}x{screen_height}')
root.configure(bg="#0f4c81")
root.resizable(0,0)
root.title('Time')
(2)日期显示
#显示日期
date = time.strftime("%Y/%m/%d")
tk.Label(root,text = date,bg="#0f4c81",fg='#00FFFF',font=("微软雅黑",50)).place(x=100,y=100)
3.时间实时显示实现
# 获取时间的函数
def gettime():
# 获取当前时间
dstr.set(time.strftime("%H:%M:%S"))
# 每隔 1s 调用一次 gettime()函数来获取时间
root.after(1000, gettime)
# 生成动态字符串
dstr = tk.StringVar()
# 利用 textvariable 来实现文本变化
lb = tk.Label(root,textvariable=dstr,bg="#0f4c81",fg='#00FFFF',font=("微软雅黑",150))
lb.place(x=500,y=300)
4.退出按钮实现
def exit_root():
root.destroy()
exit_btn = tk.Button(root,text="退出",command=exit_root)
exit_btn.place(x=int(screen_width)-100,y=int(screen_height)-100)
5.调用时间显示函数与界面运行
# 调用生成时间的函数
gettime()
# 显示窗口
root.mainloop()
6.完整源码分享
import tkinter as tk
import time
root = tk.Tk()
root.title("时间")
root.attributes('-fullscreen', True)
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
root.geometry(f'{screen_width}x{screen_height}')
root.configure(bg="#0f4c81")
root.resizable(0,0)
root.title('Time')
#显示日期
date = time.strftime("%Y/%m/%d")
tk.Label(root,text = date,bg="#0f4c81",fg='#00FFFF',font=("微软雅黑",50)).place(x=100,y=100)
# 获取时间的函数
def gettime():
# 获取当前时间
dstr.set(time.strftime("%H:%M:%S"))
# 每隔 1s 调用一次 gettime()函数来获取时间
root.after(1000, gettime)
# 生成动态字符串
dstr = tk.StringVar()
# 利用 textvariable 来实现文本变化
lb = tk.Label(root,textvariable=dstr,bg="#0f4c81",fg='#00FFFF',font=("微软雅黑",150))
lb.place(x=500,y=300)
def exit_root():
root.destroy()
exit_btn = tk.Button(root,text="退出",command=exit_root)
exit_btn.place(x=int(screen_width)-100,y=int(screen_height)-100)
# 调用生成时间的函数
gettime()
# 显示窗口
root.mainloop()