How to Create an Alarm Clock App using Tkinter in Python

Learn how to build a simple alarm clock app using tkinter and playsound libraries in Python.
  · · 5 min read · Updated nov 2022 · GUI Programming

Juggling between coding languages? Let our Code Converter help. Your one-stop solution for language conversion. Start now!

An alarm clock is an essential part of us. We rely on it to remind us of the time we need to do a particular task. Creating one in Python is not that hard. In this tutorial, we will make a simple alarm clock in Python with the help of the following libraries:

  • tkinter - This Graphical User Interface (GUI) library lets us display the alarm clock UI.
  • playsound - Helps us create sounds for our alarm clock.
  • time - Provides time-related functions
  • datetime - makes it simpler to access attributes of the thing associated with dates, times, and time zones.
  • threading - It provides asynchronous execution of some functions in an application. To install the modules in the command line interface
$ pip install playsound
  • datetime, time and tkinter modules come pre-installed with Python.

To import in our code editor:

from tkinter import *
import datetime
import time
from playsound import playsound
from threading import *

import * means we are importing all libraries from the Tkinter module.

We then design how the graphical user interface will look by using tkinter:

root = Tk()  # initializes tkinter to create display window
root.geometry('450x250')  # width and height of the window
root.resizable(0, 0)  # sets fix size of window
root.title(' Alarm Clock')  # gives the window a title


addTime = Label(root, fg="red", text="Hour     Min     Sec",
                font='arial 12 bold').place(x=210)
setYourAlarm = Label(root, text="Set Time(24hrs): ",
                     bg="grey", font="arial 11 bold").place(x=80, y=40)
hour = StringVar()
min = StringVar()
sec = StringVar()

# make the time input fields
hourTime = Entry(root, textvariable=hour, relief=RAISED, width=4, font=(20)).place(x=210, y=40)
minTime = Entry(root, textvariable=min, width=4, font=(20)).place(x=270, y=40)
secTime = Entry(root, textvariable=sec, width=4, font=(20)).place(x=330, y=40)

We design the interface by setting its width and height and giving it a title. We then create two labels, one to show us where to enter hours, minutes, and seconds, and the other to guide us on where to set the time. Using Entry(), we also create where the data will be input.

StringVar() specifies the variable type whereby hourmin and sec are all string variables.

Our interface now looks like this:


Great. Let's now create the main alarm() function that changes the remaining time every second and check whether the alarm time is reached. If so, then it plays the alarm sound and shows a simple message box:

def start_alarm():
    t1 = Thread(target=alarm)
    t1.start()


def alarm():
    while True:
        set_alarm_time = f"{hour.get()}:{min.get()}:{sec.get()}"
        # sleep for 1s to update the time every second
        time.sleep(1)
        # Get current time
        actual_time = datetime.datetime.now().strftime("%H:%M:%S")
        FMT = '%H:%M:%S'
        # get time remaining
        time_remaining = datetime.datetime.strptime(
            set_alarm_time, FMT) - datetime.datetime.strptime(actual_time, FMT)
        # displays current time
        CurrentLabel = Label(
            root, text=f'Current time: {actual_time}', fg='black')
        CurrentLabel.place(relx=0.2, rely=0.8, anchor=CENTER)
        # displays alarm time
        AlarmLabel = Label(
            root, text=f'Alarm time: {set_alarm_time}', fg='black')
        AlarmLabel.place(relx=0.2, rely=0.9, anchor=CENTER)
        # displays time remaining
        RemainingLabel = Label(
            root, text=f'Remaining time: {time_remaining}', fg='red')
        RemainingLabel.place(relx=0.7, rely=0.8, anchor=CENTER)
        # Check whether set alarm is equal to current time
        if actual_time == set_alarm_time:
            # Playing sound
            playsound('audio.mp3')
            messagebox.showinfo("TIME'S UP!!!")

We also define the start_alarm() function, which establishes a Thread instance and instructs it to begin a new alarm thread with .start().

The strptime() method creates a datetime object from the given string, and takes two arguments, the string to be converted to datetime, and time format code. We converted the strings to datetime and saved them with the %H:%M:%S format. This allows us to find the time interval between the set alarm time and the current time, and save it as time_remaining.

We go ahead and create a label to display the time remaining as RemainingLabel, with its font color red. We also create two labels displaying the current and alarm times. When the current time and the set alarm time matches, a sound is played, and a message is displayed in the interface.

We add an audio file that will play when the alarm goes off, and save it in the home directory.

Now let's create a button that sets our alarm when clicked:

# create a button to set the alarm
submit = Button(root, text="Set Your Alarm", fg="red", width=20,
                command=start_alarm, font=("arial 20 bold")).pack(pady=80, padx=120)

Finally, let's run the program:

# run the program
root.mainloop()

Our interface should now look like this:

When the alarm goes off, audio.mp3 plays and a message is displayed, saying the time's up:

Conclusion

We have successfully created an alarm clock in Python; see how you can add more features to this!

Get the complete code here.

Learn also: How to Make an Age Calculator in Python.

Happy coding ♥

Just finished the article? Now, boost your next project with our Python Code Generator. Discover a faster, smarter way to code.

View Full Code Assist My Coding
Sharing is caring!



Read Also



Comment panel

    Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!