AstroPy basic



Lesson: clock alarm; 鬧鐘程式範例, 定時播放聲音當作爲鬧鐘


此程式利用tk作為圖形化介面, 並利用time函式庫讀取時間, 最後利用pygame函式庫播放聲音檔.
概念:此程式執行時會自動利用time.time()函式讀取目前時間, 並利用自行撰寫的addhr(),addmin()來設定鬧鐘時間(TargetTime).
主程式爲不斷的執行clock(函數), clock會比對目前時間與鬧鐘時間的時間順序, 當目前時刻超越鬧鐘時間時, 程式便會開始播放音樂
alarm.py

wave file

import tkinter as tk
import time
import pygame
TargetTime = time.time()
playMusic = 0
stopMusicbool = 0
SettingComplete = 0

def addhr():
	global TargetTime,SettingComplete
	TargetTime=TargetTime+3600
	AlarmTime.config(text="Alarm was set at "+time.strftime('%m/%d %I:%M:%S',time.localtime(TargetTime)),font=("Helvetica", 24), fg="blue")
	SettingComplete=1

def addmin():
	global TargetTime,SettingComplete
	TargetTime=TargetTime+60
	AlarmTime.config(text="Alarm was set at "+time.strftime('%m/%d %I:%M:%S',time.localtime(TargetTime)),font=("Helvetica", 24), fg="blue")
	SettingComplete=1

def clock():
	global TargetTime
	global playMusic,SettingComplete, stopMusicbool

	localtime=time.strftime('%m/%d %I:%M:%S',time.localtime())
    #localtime = time.time() #returnt the time after 1970/1/1
    #localtime = time.localtime(time.time())
    #localtime = time.asctime( time.localtime(time.time()) )
	label.config(text="current time is "+localtime,font=("Helvetica", 24), fg="blue")
	if TargetTime < time.time() and playMusic==0 and SettingComplete==1:	
		pygame.mixer.Sound('believe_me.wav').play() #please replace the file of wave file 
		playMusic=1
	if stopMusicbool==1:
		pygame.mixer.pause()		
	win.after(100,clock)
def stopMusic():
	global stopMusicbool
	stopMusicbool=1
pygame.init()

win=tk.Tk()
win.title("Tk Clock")
win.geometry('600x400')

label=tk.Label(win,justify='center')
label.pack()

ClickButtonhr=tk.Button(win, text="+hour", font=("Helvetica", 18), height = 1, width = 10, command=addhr)
ClickButtonhr.pack()

ClickButtonmin=tk.Button(win, text="+1 mins", font=("Helvetica", 18), height = 1, width = 10, command=addmin)
ClickButtonmin.pack()



AlarmTime=tk.Label(win,justify='center',font=("Helvetica", 24), text ="when should you wake up?" )
AlarmTime.pack()

ClickButtonStop=tk.Button(win, text="STOP the Alarm", font=("Helvetica", 18), height = 1, width = 20, command=stopMusic)
ClickButtonStop.pack()

clock()
win.mainloop()
result
The Interface of the code
s