1 import time 2 import tkinter as tk 3 from tkinter import messagebox 4 5 6 def main(): 7 window1 = tk.Tk() 8 window1.title('計時器【v0.0】') 9 window1.geometry('300x200') 10 11 l1 = tk.Label(window1, text='當前時間:', font=('宋體', 15)) 12 l1.place(x=5, y=10) 13 14 def time_now(): 15 global seconds_now 16 seconds_now = time.time() 17 lt = time.localtime(seconds_now) 18 time1 = [] 19 time2 = '%04d年%02d月%02d日 \n %02d時%02d分%02d秒' % (lt[0], lt[1], lt[2], lt[3], lt[4], lt[5]) 20 21 if time2 != time1: 22 time1 = time2 23 l1_2 = tk.Label(window1, text=time1, font=('宋體', 20)) 24 l1_2.configure(text=time2) 25 l1_2.place(x=30, y=50) 26 l1_2.after(200, time_now) 27 28 time_now() 29 30 def input_time(): 31 window2 = tk.Tk() 32 window2.title('計時器【v0.0】') 33 window2.geometry('300x120') 34 35 l2_1 = tk.Label(window2, text='年', font=('宋體', 15)) 36 l2_1.place(x=90, y=20) 37 l2_2 = tk.Label(window2, text='月', font=('宋體', 15)) 38 l2_2.place(x=170, y=20) 39 l2_3 = tk.Label(window2, text='日', font=('宋體', 15)) 40 l2_3.place(x=250, y=20) 41 l2_4 = tk.Label(window2, text='有效日期【1970/1/2-3001/1/1】', font=('宋體', 10)) 42 l2_4.place(x=50, y=50) 43 44 year = tk.Entry(window2, text=None, font=('宋體', 15), width=5) 45 month = tk.Entry(window2, text=None, font=('宋體', 15), width=5) 46 day = tk.Entry(window2, text=None, font=('宋體', 15), width=5) 47 year.place(x=40, y=20) 48 month.place(x=120, y=20) 49 day.place(x=200, y=20) 50 51 def get_time(): 52 try: 53 y = int(year.get()) 54 m = int(month.get()) 55 d = int(day.get()) 56 lt_ = time.strptime(f'{y} {m} {d}', '%Y %m %d') 57 seconds_get = time.mktime(lt_) 58 except BaseException: 59 tk.messagebox.showerror(message='輸入有誤!') 60 else: 61 window2.withdraw() 62 63 string1 = '查詢日期距離現在還有:' 64 string2 = '查詢日期距離現在已過去:' 65 66 seconds_lasting = seconds_get - seconds_now 67 68 day_lasting = abs(seconds_lasting) // 86400 69 month_lasting = 0 70 year_lasting = 0 71 days = day_lasting 72 73 if day_lasting > 356: 74 year_lasting = day_lasting // 365 75 day_lasting -= year_lasting * 365 76 if day_lasting > 30: 77 month_lasting = day_lasting // 30 78 day_lasting -= month_lasting * 30 79 elif day_lasting > 30: 80 year_lasting = 0 81 month_lasting = day_lasting // 30 82 day_lasting -= month_lasting * 30 83 else: 84 year_lasting, month_lasting = 0, 0 85 86 if seconds_lasting > 0: 87 prompt = string1 88 days += 1 89 day_lasting += 1 90 else: 91 prompt = string2 92 93 tk.messagebox.showinfo( 94 message='%s%d天\n大概為%d年%d月%d天' % (prompt, days, year_lasting, month_lasting, day_lasting)) 95 96 button2 = tk.Button(window2, text='開始查詢', font=('宋體', 15), command=get_time) 97 button2.place(x=110, y=75) 98 99 window2.mainloop() 100 101 button1 = tk.Button(window1, text='輸入查詢日期', font=('宋體', 15), command=input_time) 102 button1.place(x=85, y=125) 103 104 window1.mainloop() 105 106 107 if __name__ == '__main__': 108 main()