Site icon DataFlair

How to Create a Countdown Timer in Python

countdown timer in python

Python course with 57 real-time projects - Learn Python

A countdown timer is an ideal way to set targets to complete tasks eg keep a reminder for the oven etc. For large-scale applications such as industries, complex timers are used, which are custom-designed for various purposes such as triggering or flipping a switch after a delay of set time. We might have noticed a screensaver appearing on the desktop when left idle for sometime. This happens because of the timer which calculates our idle time. Similarly, automatic logging out of websites, OTP expiration, captcha expiration are all based on a timer which nullifies these password after the time period expires.

Python Countdown Timer Project:

We will create a simple countdown timer using python and display 2 notifications, one with the app created and another on the desktop to remind the user of the time elapsed. A good understanding of functions and Tkinter widgets to understand the code flow is ideal.

Project Prerequisites:

The python countdown timer project makes use of tkinter for GUI development, time module for creating a delay, and plyer to create desktop notifications. We make use of Tkinter, a built-in GUI library in python. To check its availability, import it:

python
>>> import tkinter

If the library is installed, it will not show an error. In case an error appears, use the following command to install Tkinter on a Linux system:

sudo apt-get install python3-tkinter

On Windows systems, reinstalling python will fix the issue. Time module is a built-in library and hence does not require any installation.

Now, to install plyer please run below command using pip:

pip install plyer

Download Countdown Timer Python code:

You can download the source code for the Countdown Timer in the given link: Countdown clock and timer

Project File Structure:

There are many GUI libraries supported by python such as PyQT5, Kivy, Pyside2 etc. Tkinter is widely used by many developers and is easy for beginners to practice.

Let’s have a look at the steps to python countdown timer project:

  1. Importing modules: time, tkinter, and plyer
  2. Initializing the window and declaring the dimensions
  3. Defining functions for timer and placeholders
  4. Creating the user input interface
  5. Addition of a button to activate the timer

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

Now let’s discuss the complete implementation in detail.

Feel free to play with the values and change your input methods.

1. Importing necessary modules:

#DataFlair Guide for python Countdown Timer
#Import necessary modules
from plyer import notification
from tkinter import messagebox
from tkinter import *
import time

Code Explanation:

2. Initialising the window and declaring the dimensions:

#Assign class and set dimensions of the interface
window = Tk()
window.geometry("300x200")
window.title("DataFlair - python Countdown timer and notification")

Code explanation:

3. Defining functions for timer and placeholders:

#Remove the placeholders for every entry field based on click   
def h_click(event):
       hour_entry.delete(0, 'end')        
def m_click(event):
       min_entry.delete(0, 'end')
def s_click(event):         
 sec_entry.delete(0, 'end')

Code explanation:
The placeholder functions are optional.

#Function to activate python countdown timer and show notifications once timer is up
def timer():
   #Since we use placeholders, we check if the user entered an integer
   try:
       timer_time = int(hour_entry.get())*3600 + int(min_entry.get())*60 + int(sec_entry.get())
      
   except:
       messagebox.showerror(message="Enter Valid Time")
   #The user cannot activate a timer with no time set
   #To update the timer with every decreasing second and display a notification   
   if timer_time >0:
       hour = 0
       min = 0
       sec = 0   
       #If minutes is more than 60, it has to be set to the next hour
       while timer_time >= 0:
           min, sec = divmod(timer_time,60)
           if min > 60:
               hour, min = divmod(min,60)
           #Set the declared variables with the new values to display               
           hours.set(hour)
           mins.set(min)
           secs.set(sec)
           #Sleep for 1 creates a delay of 1 second
           time.sleep(1)  
           #Update the changes on the window for every second
           window.update()
           #Decrement the timer value by 1
           timer_time -= 1
       #Create a desktop notification
       notification.notify(
           #Title of the notification,
           title = "TIMER ALERT",
           #Body of the notification
           message = "Hey amigo!\nDid you do what you wanted to achieve? \nIf not, try again with a new timer",
app_icon="/home/data-flair/Downloads/python-countdown-timer/bell.ico",
           #Notification stays for 30 seconds
           timeout  = 30,
       )
       #This notification is provided by tkinter with the created app
       messagebox.showinfo(message="Timer Complete!")

Code explanation:

4. Creating the user input interface:

#Label for displaying the title of the app
#position of the label or widget is set using pack().
#pack defaults to centered alignment on a x row and y column coordinate
title_label_1=Label(window,text="DataFlair-Countdown timer with notification", font=("Gayathri", 12)).pack()
title_label_2 = Label(window, text="Put 0 in fields not of use", font=("Gayathri", 10)).pack()
#Variables using which the timer is updated in the function
hours = IntVar()
mins = IntVar()
secs = IntVar()
 
#To read user input for hours, minutes and seconds
hour_entry=Entry(window,width=3,textvariable=hours,font=("Ubuntu Mono",18))
min_entry=Entry(window,width=3,textvariable=mins,font=("Ubuntu Mono",18))
sec_entry=Entry(window,width=3,textvariable=secs,font=("Ubuntu Mono",18))
 
#Placeholder for the entry widgets
hour_entry.insert(0,00)
min_entry.insert(0,00)
sec_entry.insert(0,00)
 
#Positioning the entry widgets.
#place() takes an x(from the left) and y(from the top) coordinate
hour_entry.place(x=80,y=40)
min_entry.place(x=130,y=40)
sec_entry.place(x=180,y=40)
 
#To link the defined placeholder removal functions on mouse click
hour_entry.bind("<1>", h_click)
min_entry.bind("<1>", m_click)
sec_entry.bind("<1>", s_click)

Code explanation:

5. Addition of a button to activate the timer:

#button to activate the timer function
button = Button(window,text='Activate Timer',bg='Red', command=timer).pack(pady=40)
#Close the window and exit the app
window.mainloop()

Code explanation:
This snippet of code is optional

Python Countdown Timer Output:

Enter the time for the countdown timer and view the notification:

Summary

We have successfully created python countdown timer with plyer, tkinter and time modules. The project explores many features of Tkinter such as entry widgets, mouse clicks, buttons and placeholders. Using two ways, notifications were created and used.

Exit mobile version