Python Project for Beginners – Alarm Clock with GUI [Source Code Included]

Python course with 57 real-time projects - Learn Python

Being a beginner it’s critical to work in the right direction. To master a programming language, you should work on projects. In this article, we will develop a basic python project – Alarm clock

alarm clock python project

It is no doubt that an alarm clock is always handy to alert us whenever we sleep, take a short nap, or to remind us about the work, we always get oblivious about.

Our ancestors have been using an alarm clock, going back to its 2,000 years long history but over time, the new advancements in technologies allow us to keep an alarm clock without it containing a dial, gear trains, etc. How? Let’s find out further.

Develop an Alarm Clock

About the Python Project

The objective of our project is to implement an alarm clock using Python. Python consists of some very innovative libraries such as datetime and tkinter which help us to build the project using the current date and time as well as to provide a user interface to set the alarm according to the requirement in 24-hour format.

Prerequisites

This project requires good knowledge of Python and GUI (Graphic User Interface). Python when combined with Tkinter provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit. All the modules used need not be downloaded beforehand like the other libraries like NumPy, thus this project will be user friendly and accessible in any virtual environment used for python programming.

Project File Structure

First, let’s check the steps to build an Alarm Clock program in Python:

  • Importing all the libraries and modules required
  • Putting forward a while loop which takes the argument of the time, the user wants to set the alarm on and automatically breaks when the time is up, with sound
  • Create a display window for user input.

Download Project Code

Before proceeding ahead, please download source code: Alarm Clock Project Code

So that is basically what we will do in this Python project. Let’s start.

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

1. First, we import all the necessary libraries and modules:

#Importing all the necessary libraries to form the alarm clock:
from tkinter import *
import datetime
import time
import winsound

Explanation:

  • Tkinter module belongs to a standard library of GUI in Python. It helps us to create a dialog box with any information that we want to provide or get from the users.
  • Datetime and time modules in python help us to work with the dates and time of the current day when the user is operating python and to manipulate it too.
  • Winsound module provides access to the basic sound playing machinery provided by Windows platforms. This is useful to generate the sound immediately when a function is called.

2. Create a while loop:

def alarm(set_alarm_timer):
    while True:
        time.sleep(1)
        current_time = datetime.datetime.now()
        now = current_time.strftime("%H:%M:%S")
        date = current_time.strftime("%d/%m/%Y")
        print("The Set Date is:",date)
        print(now)
        if now == set_alarm_timer:
            print("Time to Wake up")
        winsound.PlaySound("sound.wav",winsound.SND_ASYNC)
        break

def actual_time():
    set_alarm_timer = f"{hour.get()}:{min.get()}:{sec.get()}"
    alarm(set_alarm_timer)

Explanation:

  • Define a function named as alarm() which takes the argument of (set_alarm_timer).It contains a while loop with a Boolean function True which makes the program automatic to work.
  • time.sleep(1) halts the execution of the further commands given until we get the time value from the user later in the code and returns the background thread of the clock time going on at a regular interval.
  • Get the current time using current_time which takes the argument of datetime.datetime.now().
  • now is used to print the time and date is used to print the current date by string conversion using strftime().
  • Define another function here named actual_time() which takes in the user value for setting the alarm in the string format. The same argument of (set_alarm_timer) as alarm before to execute the while loop which we further use while making GUI.
  • If loop suggests that if the user input time set_alarm_timer matches with the while loop ongoing time now, the message is printed as” Time to Wake up”.
  • winsound.SND_ASYNC plays the system generated sound as soon the condition satisfies, acting as a reminder for the alarm clock.

3. Creating GUI using tkinter:

clock = Tk()

clock.title("DataFlair Alarm Clock")
clock.geometry("400x200")
time_format=Label(clock, text= "Enter time in 24 hour format!", fg="red",bg="black",font="Arial").place(x=60,y=120)
addTime = Label(clock,text = "Hour  Min   Sec",font=60).place(x = 110)
setYourAlarm = Label(clock,text = "When to wake you up",fg="blue",relief = "solid",font=("Helevetica",7,"bold")).place(x=0, y=29)

# The Variables we require to set the alarm(initialization):
hour = StringVar()
min = StringVar()
sec = StringVar()

#Time required to set the alarm clock:
hourTime= Entry(clock,textvariable = hour,bg = "pink",width = 15).place(x=110,y=30)
minTime= Entry(clock,textvariable = min,bg = "pink",width = 15).place(x=150,y=30)
secTime = Entry(clock,textvariable = sec,bg = "pink",width = 15).place(x=200,y=30)

#To take the time input by user:
submit = Button(clock,text = "Set Alarm",fg="red",width = 10,command = actual_time).place(x =110,y=70)

clock.mainloop()
#Execution of the window.

Explanation:

  • To Initialize tkinter, we pass a command under the name clock as Tk().
  • The dialog box has the title as DataFlair Alarm Clock with a geometry of (400*200). We pass on the heading to mention the time format for 24 hours using time_format.
  • The second heading is given above the user input boxes for the labeling to be “Hour Min Sec” using addTime.
  • Just to make the dialog box look funkier, adding another label as “when to wake you up” using setYourAlarm.
  • As we have already converted the current time in the string before (actual time), the variables we initialize for the user input dialog boxes are in StringVar().
  • Finally make the input boxes such as hourTime, minTime, and secTime which takes the entry of the time the user wants to set the alarm on in 24-hour format.
  • Submit takes the command of the defined function actual_time and executes the clock as it acts as a set button to start the program.
  • Clock.mainloop() is the basic and the last command was given to compile all the previous commands with their basic settings of color, font, width, axis, etc. and displays the window as soon as the program is run.

Yay!! The alarm clock is ready for execution for your next work nap 😉. Save the source code with DataFlair-Alarm-Clock.py and run the file:

python3 DataFlair-Alarm-Clock.py

Output

alarm clock run program

Summary

With this project in Python, we have successfully made the Alarm Clock. We used the popular GUI library for rendering graphics on a display window. We learned how to extract the current time from the computer and to use it for manipulation using the DateTime library. This way we can set an alarm in the computer interface using python programming which rings with the default machine sound for Windows.

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

follow dataflair on YouTube

71 Responses

  1. Sumit Kosta says:

    You explain so good.please send me these types of important article in my e-mail

  2. Priyanuj Bora says:

    Thanks a lot !! It has been a great help !!!

  3. Sarah says:

    I get a syntax error in this ,”clock.title(“DataFlair Alarm Clock”)”

    • DataFlair Team says:

      The error might be due to improper indentation or you might not have declared ‘clock’ so make sure you have ‘clock=Tk()’ this line in your code.

  4. Prasanna Kumari.M says:

    I also get the syntax error in the line of -‘clock.title(“DataFlair Alarm Clock”)’
    What can I do?……

    • DataFlair Team says:

      The error might be due to improper indentation or you might not have declared ‘clock’ so make sure you have ‘clock=Tk()’ this line in your code.

  5. Shikhar Shukla says:

    What is the replacement of winsound for mac or Linux users?

  6. ATARI_LIVE says:

    Make sure not double same lines… I got double when I copied from here.

  7. jawed alam says:

    i also get a syntax error in this,”clock.title(“DataFlair Alarm Clock”)”

    • DataFlair Team says:

      The error might be due to improper indentation or you might not have declared ‘clock’ so make sure you have ‘clock=Tk()’ this line in your code.

  8. Inam says:

    Hi, i got an error by saying
    TclError: unknown option “-tclock” on the line 32 which is setYourAlarm = Label(clock,tclock = Tk())

    kindly provide me a solution

  9. spiros says:

    same problem. Looked at the source and saw this

    setYourAlarm = Label(clock,text = “When to wake you up”,fg=”blue”,relief = “solid”,font=(“Helevetica”,7,”bold”)).place(x=0, y=29)

    i dont know

  10. Hello says:

    I got a syntax error in

    set_alarm_timer = f”{hour.get()}:{min.get()}:{sec.get()}”

    • DataFlair Team says:

      It is the first line of the function actual_time() so you might have improper indentation. Please check your indentation and let us know if you are still facing issues.

  11. Amardeep Roychowdhury says:

    return self.tk.call(‘wm’, ‘iconbitmap’, self._w, bitmap)
    _tkinter.TclError: bitmap “dataflair-logo.ico” not defined
    I got this error

    • DataFlair Team says:

      The dataflair-logo.ico file(image) is not present in your computer, download the image and keep it in the source code folder with same name.

  12. SS says:

    Regarding, The error ““dataflair-logo.ico” not defined”
    It is coming because, this ico (image file) is not present in your local machine.
    I downloaded a sample .ico file (image) from google and renamed it with “dataflair-logo.ico” (kept in the same directory as source code, and it work fine.

  13. aman says:

    why i don’t get any alarm sound when time matched…..?

  14. aman says:

    what is that sound.wav ??

  15. Aparna says:

    Why i got syntax error in clock.mainloop?
    ^

  16. Syed khan says:

    Hello There! I set the alarm but it doesn’t rings and no sound is made . print statement for time to wake up is also not executed

  17. Prathik kamath says:

    Hey can i make a small request?…i want to add snooze button to it and it should work. But i dont know how would you please help, this is a part of my project it would be great if you could help. Thank you

    • DataFlair Team says:

      In the alarm function, you can create a snooze button and set another alarm 5 minutes from now when user clicks on snooze button. This way you don’t have to write another funtion for snooze.
      The code to set another alarm 5 min later:

      current_time = datetime.datetime.now()

      date = int(current_time.strftime(“%d”))
      month=int(current_time.strftime(“%m”))
      year= int(current_time.strftime(“%Y”))

      hrs = int(current_time.strftime(“%H “))
      mins= int(current_time.strftime(“%M”))
      secs= int(current_time.strftime(“%S”))

      mins = mins+5

      if(mins>59):
      hrs=hrs+1
      mins=mins-60

      set_alarm_timer = f”{hrs}:{mins}:{secs}”
      alarm(set_alarm_timer)

  18. ll says:

    hey, I set the alarm but it doesn’t rings and no sound is made . how i can fix it?

  19. Yersin says:

    hi! I got an error ‘_tkinter.TclError: bad geometry specifier “400*200″‘,
    even i’ve changed the size, how to fix it?!

  20. james sutton says:

    I got the error “cannot assign to function call (, line 25)” for “Label”, what should I assign label as?

    • DataFlair Team says:

      It seems you have some syntatical error in your code. Plaese download the code and match your code with it.

  21. Sunag P says:

    once we set the alarm its’s not making any sound at set alarm time.
    I’m mean it’s ringing at the time of alarm.

    • DataFlair Team says:

      Yes, alarm is designed to ring at the time of the alarm if you want specified functionality you can add this line ‘winsound.PlaySound(“sound.wav”,winsound.SND_ASYNC)’ in actual_time function.

  22. Riyan says:

    it doesnt work when i run the code, first error line about icon bitmap, after i erase it the program running, but when its my set_alarm-time = now, it doesnt ring the sound or show the ‘time to wake up’. i try to look the identation of while loop, seem okay. i’m really confused here.

  23. stark says:

    Message=’str’ object has no attribute ‘tk’
    Source=C:\Users\NAILA\source\repos\my first project\my first project\my_first_project.py
    StackTrace:
    File “C:\Users\NAILA\source\repos\my first project\my first project\my_first_project.py”, line 27, in (Current frame)
    setYourAlarm = Label(“clock”,text = “When to wake you up”,fg=”blue”,relief = “solid”,font=(“Helevetica”,7,”bold”)).place(x=0, y=29)

    i am getting problem saying” ‘str’ has no attribute tk()”

  24. Joshua Garcia says:

    so, i did every step in the code but i get “indentationErrors: unindent does not match any outer indentation level” but i don’t know how to get rid of it, when i google the error it says i could have used enter or tab key, but i only used the enter key, and don’t know what i did wrong… I’m a beginner and was hopping i could do this easily but i was wrong lol… any help from any experienced users?….. I’m using pycharm, just so you know.

  25. yogesh says:

    I have done this with visuals but the alarm doesn’t work

  26. Neo says:

    Help me,
    The alarm sound doesn’t working.

  27. Phillip M Hamilton says:

    set_alarm_timer = f”{hour.get()}: {min.get()}: {sec.get()}
    where is hour.get(), min.get() and sec.get() defined?

  28. Lauren says:

    Hi I am not getting an output even though I have save and ran the code, any suggestions

  29. Ibukun says:

    Hello, thanks for this explanation.
    I tried to run the code. The sound plays as soon as I click ‘set alarm’ but does not ring at the time set. could you help please?

  30. sera says:

    hello i am also getting an error, did you solve it?

Leave a Reply

Your email address will not be published. Required fields are marked *