Interactive Countdown Timer Using Tkinter ttkbootstrap

Setting duration for a countdown timer using ttkbootstrap Meter

Introduction

In this tutorial, we will build an interactive countdown timer using the ttkbootstrap library in Tkinter. The timer allows users to:

  • Set a countdown duration using an interactive meter widget.
  • Click the Start button to begin the countdown.
  • See the remaining time dynamically update.
  • Receive a "Time Over!" message when the countdown reaches zero.

Create an Interactive Countdown Timer in Tkinter Using ttkbootstrap meter | Python GUI Tutorial

Code Breakdown

1. Importing Required Libraries

# Import required libraries
import ttkbootstrap as tb
  • ttkbootstrap: Enhances Tkinter with modern themes and interactive widgets.

2. Function to Start the Countdown

# Function to start countdown
def start_countdown():
    duration = int(meter.amountusedvar.get())  # Get value from meter
    
    if duration == 0:
        meter.configure(subtext="Set a value!", bootstyle="danger")
        return
    
    countdown(duration)  # Start countdown
  • Retrieves the duration set in the interactive meter.
  • If the value is 0, it displays an error message.
  • Otherwise, it calls the countdown() function.

3. Countdown Logic Using after()

# Countdown function using after()
def countdown(remaining_time):
    if remaining_time >= 0:
        if root.winfo_exists():  # Check if window is open
            meter.configure(amountused=remaining_time, subtext=f"{remaining_time} sec remaining")
            root.after(1000, countdown, remaining_time - 1)
    else:
        meter.configure(subtext="Time Over!", bootstyle="danger")  # Show "Time Over"
  • Uses after(1000, function) instead of time.sleep(1) to avoid blocking the UI.
  • Updates the meter dynamically until it reaches zero.

4. Creating the Tkinter Window

# Create main window
root = tb.Window(themename="superhero")
root.title("Interactive Countdown Timer")

5. Adding the Meter Widget

# Interactive Meter Widget
meter = tb.Meter(root, bootstyle="warning", interactive=True, 
                 stripethickness=6, meterthickness=20, 
                 amountused=30, amounttotal=60, 
                 subtext="Set Time & Click Start")
meter.grid(row=0, column=0, padx=20, pady=20)

6. Adding the Start Button

# Start Button
start_button = tb.Button(root, text="Start", bootstyle="success", command=start_countdown)
start_button.grid(row=1, column=0, pady=10)

import ttkbootstrap as tb

# Function to start countdown
def start_countdown():
    duration = int(meter.amountusedvar.get())  # Get value from  meter
    
    if duration == 0:
        meter.configure(subtext="Set a value!", bootstyle="danger")
        return
    
    countdown(duration)  # Start countdown

# Countdown function using after()
def countdown(remaining_time):
    if remaining_time >= 0:
        if root.winfo_exists():  # Check if window is still open
            meter.configure(amountused=remaining_time, 
                subtext=f"{remaining_time} sec remaining")
            root.after(1000, countdown, remaining_time - 1)
        else:
            return  # Stop if window is closed
    else:
        meter.configure(subtext="Time Over!", bootstyle="danger")  # Show "Time Over"

# Create main window
root = tb.Window(themename="superhero") # change the themename 
root.title("www.plus2net.com Interactive Countdown Timer")


# Interactive Meter Widget
meter = tb.Meter(root, bootstyle="warning", interactive=True, 
                 stripethickness=6,meterthickness=20, 
                 amountused=33, amounttotal=60, 
                 subtext="Set Time & Click Start")
meter.grid(row=0, column=0, padx=20, pady=20)

# Start Button
start_button = tb.Button(root, text="Start", 
    bootstyle="success", command=start_countdown)
start_button.grid(row=1, column=0, pady=10)

# Run the application
root.mainloop()

πŸš€ Dynamic Bootstyle Update in Countdown Timer

updating bootstyle based on the value

This extension to the existing countdown timer dynamically updates the bootstyle (color) of the meter in real-time when:

  • πŸ’‘ The user manually adjusts the timer before starting the countdown.
  • ⏳ The countdown is running and time is decreasing.

πŸ”Ή get_bootstyle(value) - Function to Determine Bootstyle

This function selects the appropriate bootstyle based on the remaining time:


def get_bootstyle(value):
    if value <= 10:
        return "danger"  # Red (Critical)
    elif value <= 20:
        return "warning"  # Yellow (Caution)
    elif value <= 40:
        return "info"  # Blue (Normal)
    else:
        return "success"  # Green (Safe)

πŸ”Ή update_meter_style(*args) - Live Bootstyle Update

This function updates the meter’s bootstyle instantly when the user interacts with it.


def update_meter_style(*args):
    value = int(meter.amountusedvar.get())  # Get current meter value
    bootstyle = get_bootstyle(value)  # Get corresponding bootstyle
    meter.configure(bootstyle=bootstyle, subtext=f"{value} sec remaining")
✨ Why *args? The trace_add() function passes 3 arguments (name, index, mode), so using *args prevents errors.

πŸ”Ή Binding the Update Function to User Interaction

To ensure the bootstyle updates when the user moves the meter, we bind the function using:


meter.amountusedvar.trace_add("write", update_meter_style)

🎯 How This Enhancement Works?

  1. πŸ‘† User adjusts the meter manually β†’ bootstyle updates immediately.
  2. ⏳ When the countdown starts, the color updates dynamically.
  3. 🎨 Different colors for different time ranges:
    • πŸ”΄ 0 - 10 sec: Danger (Red)
    • 🟑 11 - 20 sec: Warning (Yellow)
    • πŸ”΅ 21 - 40 sec: Info (Blue)
    • 🟒 41+ sec: Success (Green)

πŸš€ Final Result:

βœ… Real-time Bootstyle Updates | βœ… Interactive Timer Adjustment | βœ… Smooth Countdown Color Change!

import ttkbootstrap as tb

# Function to determine bootstyle based on time value
def get_bootstyle(value):
    if value <= 10:
        return "danger"
    elif value <= 20:
        return "warning"
    elif value <= 40:
        return "info"
    else:
        return "success"

# Function to update meter style dynamically 
def update_meter_style(*args):
    value = int(meter.amountusedvar.get())  # Get current meter value
    bootstyle = get_bootstyle(value)
    meter.configure(bootstyle=bootstyle, subtext=f"{value} sec remaining")

# Function to start countdown
def start_countdown():
    duration = int(meter.amountusedvar.get())  # Get value from meter
    
    if duration == 0:
        meter.configure(subtext="Set a value!", bootstyle="danger")
        return
    
    countdown(duration)  # Start countdown

# Countdown function using after()
def countdown(remaining_time):
    if remaining_time >= 0:
        if root.winfo_exists():  # Check if window is still open
            bootstyle = get_bootstyle(remaining_time)
            meter.configure(amountused=remaining_time, 
                            subtext=f"{remaining_time} sec remaining", 
                            bootstyle=bootstyle)
            root.after(1000, countdown, remaining_time - 1)
        else:
            return  # Stop if window is closed
    else:
        meter.configure(subtext="Time Over!", bootstyle="danger")  # Show "Time Over"

# Create main window
root = tb.Window(themename="superhero")  # Change the themename
root.title("www.plus2net.com Interactive Countdown Timer")

# Interactive Meter Widget
meter = tb.Meter(root, bootstyle="success", interactive=True, 
                 stripethickness=6, meterthickness=20, 
                 amountused=33, amounttotal=60, 
                 subtext="Set Time & Click Start")
meter.grid(row=0, column=0, padx=20, pady=20)

# Bind the update function to mouse interaction (Fix: Use *args in function)
meter.amountusedvar.trace_add("write", update_meter_style)

# Start Button
start_button = tb.Button(root, text="Start", 
    bootstyle="success", command=start_countdown)
start_button.grid(row=1, column=0, pady=10)

# Run the application
root.mainloop()

Conclusion

This tutorial demonstrated how to create an interactive countdown timer using ttkbootstrap in Tkinter. The timer updates dynamically using after() and remains responsive, making it a great addition to GUI-based applications.

Integrating the Timer into Other Applications

To integrate this countdown timer into other applications, it is recommended to use threading so that the countdown runs independently without freezing the main application.

Example Use Cases

  • Typing Test: Allow users to type in a text box while the countdown runs, and disable the text box when time is over.
    Type Speed Test using countdown timer
  • Quiz Timer: Set a time limit for answering questions in a quiz application.
  • Workout Timer: Use the countdown to track exercise durations.
  • Pomodoro Technique: Implement a productivity timer for focused work sessions.

By combining threading with the ttkbootstrap countdown timer, we can build responsive and time-dependent GUI applications in Python!



Ttkbootstrap Meter bootstyle option using range Two Interlinked Meters Displaying number of chars entered in Text widget using Meter
ttkbootstrap ttkbootstrap Meter
Monitor System Performance using ttkbootstrap Meter and psutil

Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer