Step-by-Step Guide: Countdown Timer with Alarm in Python

Rick Friedman/GettyImages
facebooktwitterreddit

As part of our beginner’s look into the Python programming language, we wanted to bring you another script that’s easy to build and useful to anyone who spends a lot of time in front of the computer. A countdown timer is just such an application, and in just a few minutes, you’ll be able to click a button To open up a timer without needing to search the Internet or dig through your smartphone apps.

Why Build a Countdown Timer with Alarm Sound

Building this countdown timer with alarm sound is a great project for beginners to learn a few new tricks, including the countdown timer, which programmers use in many programs and games. We’re also going to use a GUI with this script so it gets out of the command prompt, and this is our first project to use sound which is an essential part of any game or app.

Install Required Libraries

The first thing you need to do when starting any new program is install any required libraries. Luckily, we only need to install one library for this program, Pygame. The other library we need for this program, Tkinter, has been preinstalled. Run the following line of code in your command window to install Pygame before you start to work on the code. Pygame will play the alarm sound, while Tkinter will be responsible for the graphic user interface.

pip install pygame

Easy Countdown Timer with Alarm Sound Code Explanation

In this next section, we’re going to quickly break down the code so you understand what’s happening, and at the end, we’ll provide the complete code that you can copy and paste into a Python file and use if you want.

Import Libraries

With the libraries installed, we can import them, and that’s what we’re doing with this next bit of code.

import time

import tkinter as tk

from tkinter import messagebox

import pygame

Initialize Pygame

Initialize the Pygame mixer to prepare it for playing sound. This step ensures the player is ready to go when we need it.

pygame.mixer.init()

Define the Countdown Function

Now, we get to have a little fun as we create the function for the countdown. It will use a minute-second format, but it’s important to ensure your input of value in each field when you are using it, or the script will throw an error. For instance, you can’t simply type 15 into the minutes if you want a 15-minute timer. You need to type 15 into the minute and zero into the seconds before you press Start. If you want a 30-second timer, you still need to type zero into the minutes.

The countdown function is also where we assign our mp3

  • You will need to use an mp3 (or wav) from your library. If you don’t have one, there are a lot of websites like Pixabay that offer free downloads and are sure to have something you can use.
  • It needs to be in the same folder as the Python Countdown Timer script
  • You’ll need to change its name to alarm.mp3 or change the code in the function to match the name of the one you are using

def countdown(count, label):

mins, secs = divmod(count, 60)

time_format = '{:02d}:{:02d}'.format(mins, secs)

label.config(text=time_format)

if count > 0:

root.after(1000, countdown, count-1, label)

else:

pygame.mixer.music.load('alarm.mp3')

pygame.mixer.music.play()

messagebox.showinfo("Time's up!", "Time's up!")

Create the GUI

Set up the main application window with Tkinter. We’ll create input fields for minutes and seconds, a label to display the countdown, and a button to start the timer. You can change the size of the box in this function as well as the font and size of the text.

root = tk.Tk()

root.title("Countdown Timer")

# Set the window size

root.geometry("300x200")

# Create the input fields and labels

input_label_minutes = tk.Label(root, text="Enter minutes:")

input_label_minutes.pack()

time_entry_minutes = tk.Entry(root)

time_entry_minutes.pack()

input_label_seconds = tk.Label(root, text="Enter seconds:")

input_label_seconds.pack()

time_entry_seconds = tk.Entry(root)

time_entry_seconds.pack()

# Create the countdown display label

timer_label = tk.Label(root, text="00:00", font=("Helvetica", 48))

timer_label.pack()

# Create the start button

def start_timer():

try:

minutes = int(time_entry_minutes.get())

seconds = int(time_entry_seconds.get())

total_seconds = minutes * 60 + seconds

countdown(total_seconds, timer_label)

except ValueError:

messagebox.showerror("Invalid input", "Please enter valid numbers for minutes and seconds")

start_button = tk.Button(root, text="Start", command=start_timer)

start_button.pack()

# Run the application

root.mainloop()

Full Code

import time

import tkinter as tk

from tkinter import messagebox

import pygame

# Initialize pygame mixer for playing sound

pygame.mixer.init()

def countdown(count, label):

mins, secs = divmod(count, 60)

time_format = '{:02d}:{:02d}'.format(mins, secs)

label.config(text=time_format)

if count > 0:

root.after(1000, countdown, count-1, label)

else:

pygame.mixer.music.load('alarm.mp3')

pygame.mixer.music.play()

messagebox.showinfo("Time's up!", "Time's up!")

root = tk.Tk()

root.title("Countdown Timer")

# Set the window size

root.geometry("300x200")

# Create the input fields and labels

input_label_minutes = tk.Label(root, text="Enter minutes:")

input_label_minutes.pack()

time_entry_minutes = tk.Entry(root)

time_entry_minutes.pack()

input_label_seconds = tk.Label(root, text="Enter seconds:")

input_label_seconds.pack()

time_entry_seconds = tk.Entry(root)

time_entry_seconds.pack()

# Create the countdown display label

timer_label = tk.Label(root, text="00:00", font=("Helvetica", 48))

timer_label.pack()

# Create the start button

def start_timer():

try:

minutes = int(time_entry_minutes.get())

seconds = int(time_entry_seconds.get())

total_seconds = minutes * 60 + seconds

countdown(total_seconds, timer_label)

except ValueError:

messagebox.showerror("Invalid input", "Please enter valid numbers for minutes and seconds")

start_button = tk.Button(root, text="Start", command=start_timer)

start_button.pack()

# Run the application

root.mainloop()

Follow geeks cited for more Python tutorials and to leave comments and ask questions.

manual