Python 入门学习(壹)上机时间提醒
- 基于 Udacity 的 Python 入门课程 Programming Foundations with Python
- 基于 Python 2.7
控制台版本
思路
Project 1 是一个时间提醒助手,从打开程序开始计时,每两个小时打开一个 Youtube 上的视频链接。我想也许能够做一个更完善的版本——以开机时间为原点,计算上机的时长,每两个小时弹出一个 MessageBox 提示休息。
代码
import time import os from datetime import datetime import psutil import sys from time import sleep import Tkinter as tk import tkMessageBox count = 0 while 1: os.system('cls') #清屏实现动态显示 bTime = datetime.fromtimestamp(psutil.boot_time()) #获取开机时间 print "Boot Time:", #不换行输出 print bTime cTime = datetime.now() #获取当前时间 print "Current Time:", print cTime dTime = (cTime - bTime) #计算用机时长 print "Running Seconds:", print dTime.seconds, print "s" time = int(dTime.seconds) if (time/7200 > count): tkMessageBox.showinfo(title = 'Notice', message = 'You Should Have a Rest') #弹出提示框 count+=1 sleep(1) if __name__=="__main__": main()
效果
GUI 版本
思路
既然都用上了 Tkinter,何不直接来一个 GUI 界面呢。不过如果是 Tkinter 的话,代码就需要完全重构了。
代码
#coding=utf-8 import os from datetime import datetime import psutil import sys from time import sleep from Tkinter import * import tkMessageBox import time def tick(): global time1 # 获取当前系统时间 time2 = time.strftime('%H:%M:%S') # 动态显示 if time2 != time1: time1 = time2 clock.config(text=time2) clock.after(200, tick) def timer(): global dTime1 bTime = datetime.fromtimestamp(psutil.boot_time()) cTime = datetime.now() dTime2 = (cTime - bTime).seconds if dTime2 != dTime1: dTime1 = dTime2 runn.config(text=str(dTime2)+' s') runn.after(800, timer) def msg(): global count if (dTime1/7200 > count): tkMessageBox.showinfo(title = 'Notice', message = 'You Should Have a Rest Now') count+=1 tips.config(text="累计提示次数:"+str(count)) tips.after(800, msg) root = Tk() #标题栏 root.title('Tik') #窗体尺寸 #root.geometry('200x100') #时钟 nclock = Label(root, text="当前时间", font=('DengXian', 15, 'bold'), relief=GROOVE) nclock.grid(row=0, column=0) time1 = '' clock = Label(root, font=('DengXian', 15, 'bold')) clock.grid(row=0, column=1) tick() #开机时间 nboot = Label(root, text="开机时间", font=('DengXian', 15, 'bold'), relief=GROOVE) nboot.grid(row=1, column=0) boottime = datetime.fromtimestamp(psutil.boot_time()) boottime = boottime.strftime('%H:%M:%S') boot = Label(root, text=boottime, font=('DengXian', 15, 'bold')) boot.grid(row=1, column=1) #运行时长 nrun = Label(root, text="运行时长", font=('DengXian', 15, 'bold'), relief=GROOVE) nrun.grid(row=2, column=0) dTime1 = '' runn = Label(root, font=('DengXian', 15, 'bold')) runn.grid(row=2, column=1) timer() #运行状态 status = Label(root, text=" [ Running ] ", fg = 'green', bg = 'black', font=('DengXian', 10, 'bold')) status.grid(row=10, column=0) count = 0 tips = Label(root, fg = 'green', bg = 'black', font=('DengXian', 10, 'bold')) tips.grid(row=10, column=1) msg() root.mainloop()
效果
作者:rhinoc
来源:http://rhinoc.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者允许必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任权利。