toast to show alert message

Ttkbootstrap toast
The ToastNotification widget in ttkbootstrap allows us to create pop-up messages that disappear after a certain duration.

Parameters


titleTitle of the alert window .
textMessage or text to be displayed on alert window.
durationIn Milli seconds, to show the message. If not provided then window closes on click.
bootstyleStyle keyword, options are
primary, secondary, success,info,warning,danger, light, dark
alertTrue / False : To sound the alert beep while displaying the window.
iconA unicode character to display on the top-left hand corner of the toast.
iconfontThe font used to render the icon.
positiontuple ( x, y, anchor ). 'ne' is the anchor by default. n, e, s, w, nw, ne, sw, se
**kwargsOther keyword arguments.


Toast of Ttkbootstrap to show Help text with duration and position #15


import ttkbootstrap as ttk
from ttkbootstrap.constants import *
from ttkbootstrap.toast import ToastNotification

# Create Main Window
my_w = ttk.Window(themename="lumen")
my_w.geometry("300x200")  # Width and height

# Create Toast Notification
toast = ToastNotification(
    title="This is title of Notification",
    message="Welcome to plus2net.com to learn Python",
    position=(400, 300, "ne"),
    alert=True,
    duration=5000,
    bootstyle=SUCCESS
)

# Display the Toast Notification
toast.show_toast()

# Run the Tkinter Main Loop
my_w.mainloop()

Using hide_toast() and show_toast().

Ttkbootstrap show hide toast Notification
On click of a button the toast will open by using show_toast() and by click of another button we can hide by using hide_toast().
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
from ttkbootstrap.toast import ToastNotification

# Create Main Window
my_w = ttk.Window(themename="lumen")
my_w.geometry("300x200")  # Set window width and height

# Create Toast Notification
toast = ToastNotification(
    title="This is the title of Notification",  # Notification title
    message="Welcome to plus2net.com to learn Python",  # Notification message
    position=(400, 250, "ne"),  # Position at (400, 250) aligned to top-right
    bootstyle=DANGER  # Use danger style for red theme
)

# Buttons to show and hide the toast notification

b1 = ttk.Button(
    my_w, 
    text="Open Toast", 
    command=lambda: toast.show_toast(),  # Show toast on button click
    bootstyle=SUCCESS  # Green success button
)
b1.grid(row=1, column=1, padx=10, pady=30)  # Position button in grid

b2 = ttk.Button(
    my_w, 
    text="Close Toast", 
    command=lambda: toast.hide_toast(),  # Hide toast on button click
    bootstyle=DANGER  # Red danger button
)
b2.grid(row=1, column=2, padx=10, pady=30)  # Position button in grid

# Run the Tkinter Main Loop
my_w.mainloop()

πŸ”₯ Unicode Symbols for ToastNotification in ttkbootstrap

Here is a list of Unicode symbols that you can use as icons in ToastNotification. Each row includes the symbol, Unicode code, and a working example.

πŸ“Œ Unicode Symbols for Notifications

Symbol Unicode Code Example Code
βœ… Checkmark "\u2705"
toast = ToastNotification(title="Success", 
	message="Task completed!", icon="\u2705")
❌ Cross Mark "\u274C"
toast = ToastNotification(title="Error", 
	message="Operation failed!", icon="\u274C")
⚠️ Warning "\u26A0"
toast = ToastNotification(title="Warning", 
	message="Be careful!", icon="\u26A0")
ℹ️ Info "\u2139"
toast = ToastNotification(title="Information",
	message="Did you know?", icon="\u2139")
πŸ”” Bell "\U0001F514"
toast = ToastNotification(title="Reminder", 
message="You have a new notification!", icon="\U0001F514")
πŸ† Trophy "\U0001F3C6"
toast = ToastNotification(title="Achievement", 
	message="You won an award!", icon="\U0001F3C6")
πŸ”₯ Fire "\U0001F525"
toast = ToastNotification(title="Alert", 
	message="High priority!", icon="\U0001F525")

πŸš€ Example Usage

import ttkbootstrap as ttk
from ttkbootstrap.toast import ToastNotification

root = ttk.Window(themename="superhero")

toast = ToastNotification(
    title="Success!",
    message="Your operation completed successfully.",
    duration=3000,  # 3 seconds
    icon="\u2705",  # βœ… Checkmark Unicode
    bootstyle="success"
)

toast.show_toast()

root.mainloop()

πŸ“ Notes

  • The icon parameter in ToastNotification accepts Unicode symbols to enhance user experience.
  • Using Unicode symbols makes notifications more visually appealing than plain text.
  • Experiment with different Unicode characters for a customized look.

Advanced Customization of Toast Notifications

To enhance user experience, we can customize its position, icon, and interactivity. Let's explore advanced configurations and use cases.

Example 1: Customizing Toast Position and Icon

This example demonstrates how to position the toast at specific screen coordinates and use a custom icon.

# Import necessary modules
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
from ttkbootstrap.toast import ToastNotification

# Initialize the main window
app = ttk.Window(themename="lumen")
app.geometry("300x200")

# Create a toast notification
toast = ToastNotification(
    title="Custom Icon and Position",
    message="This toast appears at (500, 500) with a custom icon.",
    duration=4000,
    bootstyle=SUCCESS,
    icon="\u2705", # Checkmark icon
    position=(500, 500, 'ne')
)

# Display the toast
toast.show_toast()

# Run the application
app.mainloop()

Position relative to window size

# Get screen width and height
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()

# Calculate center position for the toast
toast_x = screen_width // 2
toast_y = screen_height // 2
Check the example given below to position the toast message at center position.

Example 2: Interactive Toast with Buttons

In this example, we create buttons to show and hide the toast dynamically.

# Import necessary modules
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
from ttkbootstrap.toast import ToastNotification

# Initialize the main window
app = ttk.Window(themename="lumen")
app.geometry("300x200")

# Create a toast notification
toast = ToastNotification(
    title="Interactive Toast",
    message="Click buttons to show or hide this toast.",
    bootstyle=INFO
)

# Define button commands
def show_toast():
    toast.show_toast()

def hide_toast():
    toast.hide_toast()

# Create buttons
show_button = ttk.Button(app, text="Show Toast", command=show_toast, bootstyle=SUCCESS)
show_button.pack(pady=10)

hide_button = ttk.Button(app, text="Hide Toast", command=hide_toast, bootstyle=DANGER)
hide_button.pack(pady=10)

# Run the application
app.mainloop()

Mouse enter and leave events with Toast Notifications

Mouse hover events and toast notification

We will allow users to hover over buttons representing different fruits, and a toast notification will appear with information about the fruit. The notification will disappear once the mouse moves away. Additionally, we will tackle the issue of overlapping toast notifications and how to fix it.

Problem Faced: Overlapping Toasts

Initially, we encountered an issue where multiple toast notifications were created if the mouse was moved quickly over different buttons. This caused overlapping notifications and a cluttered UI.

The reason for this behavior was that each time the mouse entered a button, a new toast was created without closing the previous one ( Note the time delay in closing ). As a result, multiple toasts remained on the screen at the same time.

Solution: Managing Toasts Properly

To fix this issue, we implemented the following changes:

  • Used a global variable active_toast to track the currently active toast.
  • Before creating a new toast, we explicitly hide the existing one to prevent stacking.
  • Ensured the toast disappears immediately when the mouse leaves the button.

πŸ”₯ Tkinter ttkbootstrap Toast Notifications on Mouse Hover & Mouse Out | Python GUI

Final Working Code

import ttkbootstrap as ttk
from ttkbootstrap.toast import ToastNotification

# Create Main Window
root = ttk.Window(themename="flatly")  
root.geometry("500x200")  
root.title("Fruit Info with Toast")  

# Get screen width and height
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()

# Calculate center position for the toast
toast_x = screen_width // 2
toast_y = screen_height // 2

# Fruit Data Dictionary
fruits = {
    "Apple": "Apples are rich in fiber and vitamin C.",
    "Banana": "Bananas provide instant energy and are high in potassium.",
    "Cherry": "Cherries are packed with antioxidants and promote sleep.",
    "Mango": "Mangoes are high in vitamin A and great for the skin."
}

# Global variable to track active toast
active_toast = None  

# Function to Show Toast and Prevent Overlapping
def show_toast(fruit_name):
    global active_toast
    if active_toast:  
        active_toast.hide_toast()  # Hide the previous toast before creating a new one

    # Create a new toast notification
    active_toast = ToastNotification(
        title="Fruit Info",
        message=fruits[fruit_name],
        duration=None,  # Keep it visible until manually hidden
        bootstyle="info",
        position=(toast_x, toast_y, "center")  
    )
    active_toast.show_toast()  

# Function to Hide Toast Immediately on Mouse Out
def hide_toast(event=None):
    global active_toast
    if active_toast:
        active_toast.hide_toast()  
        active_toast = None  

# Create a Frame for Buttons (Using Grid Layout)
frame = ttk.Frame(root)
frame.grid(row=0, column=0, padx=10, pady=20)

# Add Buttons in a Single Row (Using Grid)
for col, fruit in enumerate(fruits.keys()):
    btn = ttk.Button(frame, text=fruit, bootstyle="primary", width=12)
    btn.grid(row=0, column=col, padx=10, pady=5)

    # Bind mouse events
    btn.bind("<Enter>", lambda e, f=fruit: show_toast(f))  # Show toast on hover
    btn.bind("<Leave>", hide_toast)  # Hide toast immediately on mouse out

# Run Application
root.mainloop()

Key Features of This Solution

  • Ensures only one toast is visible at a time.
  • Immediately hides the toast when the mouse leaves a button.
  • Uses grid layout for structured button placement.
  • Centers the toast dynamically using winfo_screenwidth() and winfo_screenheight().

Final Thoughts

By properly managing the toast notifications, we ensure a smooth and clean user experience. The use of a global variable to track active toasts and immediate hiding on mouse leave prevents multiple overlapping messages. This method can be further extended for different types of notifications in Tkinter applications.

Now, the toast appears only when needed and disappears immediately when the mouse leaves! πŸš€

Practical Use Cases

Toast notifications can be useful in many scenarios, including:

  • Form Submission Alerts: Display a confirmation message when a form is submitted successfully.
  • System Warnings: Show low battery, network failure, or other critical warnings.
  • Live Data Updates: Notify users when new messages or updates arrive in an application.
  • Task Completion: Inform users when a background task or file download is complete.

Conclusion

Toast notifications in ttkbootstrap provide an easy way to display alerts and status messages in Tkinter applications. By customizing their position, icons, and interactivity, we can enhance user experience and provide real-time feedback. Whether for form submissions, background processes, or important alerts, toasts are a valuable addition to any GUI.

Showing ToolTip on Mouse Hovering
ttkbootstrap
Subhendu Mohapatra β€” author at plus2net
Subhendu Mohapatra

Author

πŸŽ₯ Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



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 Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer