Movatterモバイル変換


[0]ホーム

URL:


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

Step up your coding game withAI-powered Code Explainer. Get insights like never before!

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 andtkinter modules come pre-installed with Python.

To import in our code editor:

from tkinter import *import datetimeimport timefrom playsound import playsoundfrom 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 windowroot.geometry('450x250')  # width and height of the windowroot.resizable(0, 0)  # sets fix size of windowroot.title(' Alarm Clock')  # gives the window a titleaddTime = 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 fieldshourTime = 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 thestart_alarm() function, which establishes aThread 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 alarmsubmit = 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 programroot.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 codehere.

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

Happy coding ♥

Ready for more? Dive deeper into coding with ourAI-powered Code Explainer. Don't miss it!

View Full Code Explain The Code for Me
Sharing is caring!



Read Also


How to Make an Age Calculator in Python
How to Make a YouTube Audio Downloader in Python
How to Build a Spreadsheet App with Tkinter in Python

Comment panel

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





    Ethical Hacking with Python EBook - Topic - Top


    Join 50,000+ Python Programmers & Enthusiasts like you!



    Tags


    New Tutorials

    Popular Tutorials


    Ethical Hacking with Python EBook - Topic - Bottom

    CodingFleet - Topic - Bottom






    Claim your Free Chapter!

    Download a Completely Free Ethical hacking with Python from Scratch Chapter.

    See how the book can help you build awesome hacking tools with Python!



    [8]ページ先頭

    ©2009-2025 Movatter.jp