Tkinter ttkbootstrap Messagebox Tutorial

The ttkbootstrap Messagebox module replaces standard OS-native Tkinter popups with modern, theme-synchronized dialog boxes for alerts, confirmations, warnings, and error notifications.

Tutorial Breakdown:

Part I: Basic Alert Dialogs (Info, Warning, Error)

ttkbootstrap Messagebox Basic Alerts Unlike standard Tkinter messagebox, ttkbootstrap.dialogs.Messagebox renders custom themed windows with colored headers and icons.

We used ttkbootstrap Button widgets and the Pack layout manager to trigger each dialog type.

import ttkbootstrap as ttk
from ttkbootstrap.constants import *
from ttkbootstrap.dialogs import Messagebox

app = ttk.Window(title="Messagebox Alerts Demo", themename="flatly")
app.geometry("420x280")

ttk.Label(app, text="Click a button to open a themed Messagebox:", font=("Helvetica", 11, "bold")).pack(pady=15)

ttk.Button(
    app,
    text="Show Info",
    bootstyle=INFO,
    width=22,
    command=lambda: Messagebox.show_info("Export completed successfully.", title="Information", parent=app)
).pack(pady=6)

ttk.Button(
    app,
    text="Show Warning",
    bootstyle=WARNING,
    width=22,
    command=lambda: Messagebox.show_warning("Disk space is running low.", title="Warning", parent=app)
).pack(pady=6)

ttk.Button(
    app,
    text="Show Error",
    bootstyle=DANGER,
    width=22,
    command=lambda: Messagebox.show_error("Unable to connect to server.", title="Error", parent=app)
).pack(pady=6)

ttk.Button(
    app,
    text="Show Question",
    bootstyle=PRIMARY,
    width=22,
    command=lambda: Messagebox.show_question("Do you want to review the logs?", title="Question", parent=app)
).pack(pady=6)

app.mainloop()
Practical Overview

The ttkbootstrap Messagebox class provides static methods such as show_info(), show_warning(), show_error(), yesno(), okcancel(), and retrycancel(). Passing parent=app ensures the dialog centers cleanly over your main application window and inherits the active theme.

Part II: Interactive Confirmation Dialogs & Return Values

ttkbootstrap Messagebox Confirmation Return Values Confirmation dialogs return the exact button label clicked by the user (such as "Yes", "No", "OK", "Cancel", or "Retry"), or None if closed via the title bar.

We used Grid layout manager and updated a Label based on the user's choice.

Method Buttons Displayed Possible Return Values
Messagebox.yesno() Yes, No "Yes", "No", or None
Messagebox.yesnocancel() Yes, No, Cancel "Yes", "No", "Cancel", or None
Messagebox.okcancel() OK, Cancel "OK", "Cancel", or None
Messagebox.retrycancel() Retry, Cancel "Retry", "Cancel", or None
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
from ttkbootstrap.dialogs import Messagebox

def ask_yes_no():
    ans = Messagebox.yesno("Proceed with report generation?", title="Confirm Action", parent=app)
    if ans == "Yes":
        lbl_result.config(text="User clicked: Yes (Generating...)", bootstyle=SUCCESS)
    else:
        lbl_result.config(text=f"Action cancelled (Returned: {ans})", bootstyle=SECONDARY)

def ask_ok_cancel():
    ans = Messagebox.okcancel("Overwrite existing output file?", title="Overwrite Warning", alert=True, parent=app)
    lbl_result.config(text=f"OK/Cancel Result: {ans}", bootstyle=INFO)

def ask_retry_cancel():
    ans = Messagebox.retrycancel("Network timeout occurred. Try again?", title="Connection Issue", parent=app)
    lbl_result.config(text=f"Retry/Cancel Result: {ans}", bootstyle=WARNING)

app = ttk.Window(title="Confirmation Dialogs Demo", themename="cosmo")
app.geometry("450x200")

ttk.Button(app, text="Yes / No", command=ask_yes_no, bootstyle=SUCCESS).grid(row=0, column=0, padx=12, pady=25)
ttk.Button(app, text="OK / Cancel", command=ask_ok_cancel, bootstyle=PRIMARY).grid(row=0, column=1, padx=12, pady=25)
ttk.Button(app, text="Retry / Cancel", command=ask_retry_cancel, bootstyle=DANGER).grid(row=0, column=2, padx=12, pady=25)

lbl_result = ttk.Label(app, text="Click any confirmation button above", font=("Helvetica", 10, "bold"))
lbl_result.grid(row=1, column=0, columnspan=3, padx=15, pady=15)

app.mainloop()

Part III: Live Dynamic Theme Switcher

ttkbootstrap Messagebox Theme Switcher
We used StringVar and Radiobutton widgets to switch themes live.

Because Messagebox builds its dialog window dynamically when invoked, switching app.style.theme_use() immediately updates future dialog backgrounds, button colors, and borders.

import ttkbootstrap as ttk
from ttkbootstrap.constants import *
from ttkbootstrap.dialogs import Messagebox

def change_theme():
    selected_theme = theme_var.get()
    app.style.theme_use(selected_theme)
    label_info.config(text=f"Active Theme: {selected_theme}")

def preview_dialog():
    Messagebox.yesno(
        f"This dialog is styled with the '{theme_var.get()}' theme!",
        title="Themed Messagebox",
        parent=app
    )

app = ttk.Window(title="Messagebox Theme Switcher", themename="superhero")
app.geometry("450x240")

theme_var = ttk.StringVar(value="superhero")
themes = ["cosmo", "flatly", "superhero", "darkly"]

lbl_title = ttk.Label(app, text="Select Application Theme:", font=("Helvetica", 11, "bold"))
lbl_title.grid(row=0, column=0, columnspan=4, padx=15, pady=15, sticky="w")

for idx, t_name in enumerate(themes):
    rb = ttk.Radiobutton(
        app,
        text=t_name.capitalize(),
        value=t_name,
        variable=theme_var,
        command=change_theme,
        bootstyle="outline-toolbutton"
    )
    rb.grid(row=1, column=idx, padx=6, pady=5)

btn_test = ttk.Button(app, text="Open Themed Messagebox", command=preview_dialog, bootstyle=INFO)
btn_test.grid(row=2, column=0, columnspan=4, padx=15, pady=20)

label_info = ttk.Label(app, text="Active Theme: superhero", bootstyle=SUCCESS, font=("Helvetica", 10))
label_info.grid(row=3, column=0, columnspan=4, padx=15, pady=5)

app.mainloop()

Part IV: SQLite Database Integration (Delete Confirmation Guard)

ttkbootstrap Messagebox SQLite Delete Confirmation A primary real-world use of Messagebox is guarding destructive database operations.
We used SQLite database, SQLAlchemy, and a Combobox to select a student record and require explicit confirmation via Messagebox.yesno() before executing a DELETE query.

1️⃣ Creating SQLite Table & Sample Student Records

from sqlalchemy import create_engine, text

# Use raw strings r"..." to prevent Unicode escape errors in Windows paths
DATABASE_URL = r"sqlite:///I:\My Drive\testing3\ttkbootstrap\student_records.db"
# DATABASE_URL = "sqlite:///student_records.db"
engine = create_engine(DATABASE_URL, echo=False)

with engine.connect() as connection:
    connection.execute(text("CREATE TABLE IF NOT EXISTS students (id INTEGER PRIMARY KEY, name TEXT NOT NULL, grade TEXT NOT NULL)"))
    
    result = connection.execute(text("SELECT COUNT(*) FROM students"))
    if result.scalar() == 0:
        connection.execute(text("""
            INSERT INTO students (id, name, grade) VALUES 
            (101, 'Alex', 'A'),
            (102, 'Riya', 'B'),
            (103, 'John', 'A'),
            (104, 'Meera', 'C')
        """))
        connection.commit()

print("Database setup completed.")

2️⃣ Complete Application with Confirmation Guard & SQLite Delete

import ttkbootstrap as ttk
from ttkbootstrap.constants import *
from ttkbootstrap.dialogs import Messagebox
from sqlalchemy import create_engine, text

DATABASE_URL = r"sqlite:///I:\My Drive\testing3\ttkbootstrap\student_records.db"
# DATABASE_URL = "sqlite:///student_records.db"
engine = create_engine(DATABASE_URL, echo=False)
connection = engine.connect()

def load_student_list():
    rows = connection.execute(text("SELECT id, name, grade FROM students ORDER BY id")).fetchall()
    return [f"{r[0]} - {r[1]} (Grade {r[2]})" for r in rows]

def delete_selected_student():
    selected = combo_students.get()
    if not selected:
        Messagebox.show_warning("Please select a student record first.", title="No Selection", parent=root)
        return

    student_id = int(selected.split(" - ")[0])

    # Require user confirmation before deleting database record
    confirm = Messagebox.yesno(
        f"Are you sure you want to permanently delete:\n{selected}?",
        title="Confirm Delete",
        alert=True,
        parent=root
    )

    if confirm == "Yes":
        connection.execute(text("DELETE FROM students WHERE id = :sid"), {"sid": student_id})
        connection.commit()

        updated_list = load_student_list()
        combo_students["values"] = updated_list
        combo_students.set(updated_list[0] if updated_list else "")
        label_status.config(text=f"Deleted record ID {student_id}", bootstyle=DANGER)
    else:
        label_status.config(text="Deletion cancelled by user", bootstyle=SECONDARY)

root = ttk.Window(title="Messagebox SQLite Delete Guard", themename="flatly")
root.geometry("460x220")

lbl = ttk.Label(root, text="Select Student Record to Delete:", font=("Helvetica", 11, "bold"))
lbl.grid(row=0, column=0, columnspan=2, padx=15, pady=15, sticky="w")

records = load_student_list()
combo_students = ttk.Combobox(root, values=records, state="readonly", width=36, bootstyle=INFO)
if records:
    combo_students.current(0)
combo_students.grid(row=1, column=0, columnspan=2, padx=15, pady=8, sticky="ew")

btn_delete = ttk.Button(root, text="Delete Record", command=delete_selected_student, bootstyle=DANGER)
btn_delete.grid(row=2, column=0, padx=15, pady=15)

label_status = ttk.Label(root, text="Ready", font=("Helvetica", 10), bootstyle=INFO)
label_status.grid(row=2, column=1, padx=15, pady=15, sticky="w")

root.mainloop()
connection.close()

Part V: Connecting to MySQL using SQLAlchemy

To use the same confirmation guard with a centralized MySQL database server, replace the SQLite engine URL with a PyMySQL connection string. All GUI and Messagebox logic remains identical:

# SQLite Connection (Commented Out)
# DATABASE_URL = r"sqlite:///I:\My Drive\testing3\ttkbootstrap\student_records.db"

# MySQL Connection string using PyMySQL
DATABASE_URL = "mysql+pymysql://username:password@localhost/student_db"

engine = create_engine(DATABASE_URL, echo=False)
connection = engine.connect()

Common Errors & Troubleshooting

Issue / Error Cause Recommended Solution
AttributeError: module 'ttkbootstrap' has no attribute 'Messagebox' Messagebox lives inside the ttkbootstrap.dialogs submodule rather than the top-level package. Import explicitly using from ttkbootstrap.dialogs import Messagebox.
Checking if ans is True: fails Unlike standard tkinter.messagebox.askyesno() (which returns bool), ttkbootstrap returns string labels. Compare against the button string: if ans == "Yes": or if ans == "OK":.
Dialog appears in the center of the screen instead of over the app The parent parameter was omitted when calling Messagebox. Pass parent=app (or parent=root) so the dialog centers relative to your application window.

Frequently Asked Questions

Standard tkinter.messagebox invokes native operating system dialogs that ignore Tkinter themes, whereas ttkbootstrap.dialogs.Messagebox renders custom themed windows matching your active light or dark ttkbootstrap theme and returns string labels ("Yes", "No", "OK", "Cancel") instead of booleans.

Setting alert=True triggers the system notification sound (bell) when the dialog window opens, drawing immediate user attention to critical warnings or delete confirmations.

Use Messagebox.show_question() with the buttons parameter, such as buttons=['Save:success', 'Discard:danger', 'Cancel:secondary'], which returns the clicked button's text label.



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-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer