The one sound most people dread in the mornings is the beep of the Alarm Clock. However, when you code an Alarm Clock by yourself that reminds you whenever you want and gives you an option to snooze, you might not feel like breaking it. Generally, it might have been tough, but Python's Schedule Module makes our job a lot simpler.
The Simple Alarm Clock has two parts: The Back-End and the Front-End. The Back-End part contains all the scheduling and snoozing mechanism. The Front-End part is just a simple Tkinter message-box that allows you to decide whether you want to snooze or not. Let's start with the back-end:
The schedule module is the module that takes the time (in 24 hr format) and executes a function when the clock reaches that time. There are many functions under the schedule module but we will be using the schedule.every().day.at(time).do(function). Then we have a function called schedule.run_pending(), which checks if any schedule function is supposed to run at a given point of time. Putting that inside a infinite while loop keeps checking the function, forming the basic alarm function.
The next think in the backend is the snooze function. The snooze function just takes the current alarm-time, takes the minutes part by splitting the string, adds 5 to the minutes part, assigns this new time as the alarm-time and starts a new schedule function with this new time. This does not require any extreme Python knowledge. Just some string-manipulation is more than enough for the snooze function.
When we reach the front-end code, we can do a lot of things. However, the simplest thing we can do is use Tkinter's message-box to give us a question-box with a snooze and cancel option. Clicking the snooze option executes the snooze function and cancel just destroys the Tkinter root window, closing the window and message-box and uses the sys.exit() function to close the program.
Using these facts, let us try to write the code:
#Import necessary functions import schedule import time from tkinter import messagebox from tkinter import * import sys root = Tk() #Defining the snooze function def snooze(): global alarm_time hh_mm = alarm_time.split(':') hh_mm[1] = str(int(hh_mm[1]) + 5) alarm_time = ':'.join(hh_mm) schedule.every().day.at(alarm_time).do(alarm) #Defining a function for Tkinter Message-Box def alarm(): global alarm_time MsgBox = messagebox.askquestion ('Alarm-Clock','Time\'s up ! Snooze ?',icon = 'warning') if MsgBox == 'yes': snooze() else: root.destroy() sys.exit() #Getting Alarm-Time as input and scheduling alarm function for that time alarm_time = input('Enter time as hh:mm: ') schedule.every().day.at(alarm_time).do(alarm) #Checking if any schedule functions need to run while True: schedule.run_pending() time.sleep(1)
- Build a better GUI with Tkinter, Pygame and other similar modules.
- Use modules like Pygame and Mixer to add tunes to the alarm.
- Try to add a function to set more than one alarm at the same time.
Comments
Post a Comment