How To Create a Countdown Timer in Python

In this article, we’ll see how we can create a countdown timer in Python.

Steps to Run the Project

  • Install python
  • Install Pygame libraries
  • time and datetime libraries

Python Program to create Countdown Timer

import pygame
import time

# Initialize Pygame
pygame.init()

# Set up the display
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Colorful Countdown Timer")

# Define colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# Set up the countdown timer
timer_duration = 50  # Countdown duration in seconds
start_time = time.time()

# Game loop
running = True
while running:
    # Calculate the remaining time
    elapsed_time = time.time() - start_time
    remaining_time = max(timer_duration - elapsed_time, 0)

    # Handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Clear the screen
    screen.fill(WHITE)

    # Draw the countdown timer
    pygame.draw.rect(screen, RED, (100, 100, remaining_time * 10, 50))

    # Draw the text
    font = pygame.font.Font(None, 36)
    text = font.render(f"Time Left: {int(remaining_time)}", True, BLACK)
    screen.blit(text, (100, 200))

    # Update the display
    pygame.display.flip()

    # Check if the timer has reached zero
    if remaining_time == 0:
        running = False

# Quit the game
pygame.quit()

Output Count Down Timer

create a countdown timer using python features to include reset/ stop pause /resume github
timer in python code
create a countdown timer using python features to include reset/ stop pause /resume
python timer loop
python timer in seconds
python timer event
python timer class
threading timer python

Working Youtube Video

You can customize the appearance of the countdown timer by modifying the colours and the dimensions of the rectangle. Feel free to experiment and make it as colorful and cartoon-like as you want!