
Python编写电子时钟程序
发布日期:2023-05-26 13:20:23
浏览次数:2
分类:技术文章
本文共 1598 字,大约阅读时间需要 5 分钟。
电子时钟是Python中图形用户界面的一个典型例子,需要用到tkinter, time和datetime三个常用库。此程序下的电子时钟包含年月日、星期数以及时分秒,注释详细,操作简单。
import tkinter as tkimport timeimport datetime#按日期返回星期几def get_week_day(date): #用一个字典建立对应关系 dict1 = { 0: '星期一', 1: '星期二', 2: '星期三', 3: '星期四', 4: '星期五', 5: '星期六', 6: '星期天', } #取得日期对应的星期几的索引 day = date.weekday() #返回汉字的索引 return dict1[day]#每1秒钟修改一下clock_label,date_label显示值def show_time(): #取得当天星期几 week_day = get_week_day(datetime.datetime.now()) #取得现在日期和星期数 str_date = time.strftime('%Y{}%m{}%d{}').format('年', '月', '日')+week_day #取得当前时间 str_time = time.strftime('%H:%M:%S %p').format('年', '月', '日') #设置变量date_str的值 date_str.set(str_date) #设置变量time_str的值 time_str.set(str_time) #设置clock_label控件每显示1000ms调用一次show_time()函数 date_label.after(1000, show_time)if __name__ == '__main__': #生成根窗口 win = tk.Tk() #设置窗口标题 win.title('电子时钟') #设置窗口像素 win.geometry('380x160') #生成一个字符型变量,此变量与clock_label的text属性值绑定 time_str = tk.StringVar() #生成一个字符型变量,此变量与date_label的text属性值绑定 date_str = tk.StringVar() #其中textvariable=date_str将控件的text属性与变量date_str的值绑定在一起,形成联动 date_label = tk.Label(win, textvariable=date_str, bg='black', fg='white', font=('Arial', 20), width=70, height=2) #其中textvariable=time_str将控件的text属性与变量time_str的值绑定在一起,形成联动 clock_label = tk.Label(win, textvariable=time_str, bg='black', fg='white', font=('Arial', 30), width=70, height=2) #在窗体上放置Label控件 date_label.pack(anchor='center') clock_label.pack(anchor='center') #调用函数,显示新的时间 show_time() win.mainloop()
转载地址:https://blog.csdn.net/m0_74180664/article/details/128650160 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
不错!
[***.144.177.141]2023年05月16日 03时13分25秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
最新文章
路径中的 ‘\’ 与 ‘/’ 的使用区别
2020-01-28 18:15:03
cmd 常用操作
2020-01-28 18:15:03
Python mysql-数据库基础知识
2020-01-28 18:15:03
Python mysql-SQL概要
2020-01-28 18:15:03
xhr文件类型说明
2020-01-28 18:15:02
Python 爬虫-正则表达式(补)
2020-01-28 18:15:02
ASCII 可打印字符与控制字符
2020-01-28 18:15:02
Base64编码
2020-01-28 18:15:03
Python 爬虫-Scrapy框架基本使用
2020-01-28 18:15:02
24点游戏
2020-01-28 18:15:02
Python 爬虫-股票数据的Scrapy爬虫
2020-01-28 18:15:02
Python map/reduce
2020-01-28 18:15:01
Python 错误与异常
2020-01-28 18:15:01
Python 调试
2020-01-28 18:15:01
测试驱动开发(TDD)
2020-01-28 18:15:01
Python 进程与线程
2020-01-28 18:15:00
Projected Coordinate Systems
2020-01-28 18:15:00
Python random库
2020-01-28 18:15:01
Python time库
2020-01-28 18:15:01
Python 爬虫-获得大学排名
2020-01-28 18:15:00