The ttkbootstrap Messagebox module replaces standard OS-native Tkinter popups with modern, theme-synchronized dialog boxes for alerts, confirmations, warnings, and error notifications.
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()
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.
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()

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()
'darkly' and 'cosmo' still work in 2.x for backward compatibility but emit a DeprecationWarning and are planned for removal in 3.0. In ttkbootstrap 2.x, prefer the <family>-light and <family>-dark theme names (such as 'bootstrap-light', 'bootstrap-dark', 'nord-light', or 'nord-dark'), or inspect available names via app.style.theme_names().
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.
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.")
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()
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()
| 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. |
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.
alert=True triggers the system notification sound (bell) when the dialog window opens, drawing immediate user attention to critical warnings or delete confirmations.
Messagebox.show_question() with the buttons parameter, such as buttons=['Save:success', 'Discard:danger', 'Cancel:secondary'], which returns the clicked button's text label.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.