The tkinter.messagebox module provides standard system modal dialogs to display alert notifications, deliver critical warnings, and capture user confirmation choices in Python desktop GUIs.
Modal Dialog Architecture: Message boxes are blocking modal dialogs that halt parent execution until dismissed. Alerts (showinfo, showwarning, showerror) return 'ok', while confirmation dialogs (askyesno, askokcancel) return native boolean values, and askyesnocancel enables tri-state branching with None. To capture free-form input, see simpledialog. For in-window banners, see the Message widget.
| Category | Methods | Buttons | Return | Type |
|---|---|---|---|---|
| Alerts | showinfo, showwarning, showerror |
[ OK ] | 'ok' |
str |
| Binary Choice | askyesno, askokcancel, askretrycancel |
[ Yes / No ], [ OK / Cancel ] | True / False |
bool |
| Tri-State | askyesnocancel |
[ Yes / No / Cancel ] | True, False, None |
bool | None |
| Question | askquestion |
[ Yes / No ] | 'yes' / 'no' |
str |
Import messagebox separately from tkinter and invoke the target dialog function:
from tkinter import messagebox as msg
response = msg.function_name(title, message, **options)
| Parameter | Type | Default | Description |
|---|---|---|---|
title |
str |
Required | Title text displayed in the modal dialog title bar. |
message |
str |
Required | Main descriptive message displayed in the dialog body. |
default |
str |
'ok'/'yes' |
Pre-selects button activated by the Enter key (e.g. 'no', 'cancel'). |
icon |
str |
Contextual | Overrides graphic icon ('info', 'warning', 'error', 'question'). |
parent |
Widget |
None |
Locks dialog to a specific parent window, keeping it centered. |
import tkinter as tk
from tkinter import messagebox as msg
root = tk.Tk()
root.withdraw() # Hide root window
# showinfo, showwarning, and showerror return 'ok'
r1 = msg.showinfo("Update", "Download completed successfully.")
r2 = msg.showwarning("Disk Space", "Drive C: low on space.")
r3 = msg.showerror("Connection", "Could not reach database.")
print("Alert returns:", r1, r2, r3)
root.destroy()Terminal Output:
Alert returns: ok ok ok
import tkinter as tk
from tkinter import messagebox as msg
root = tk.Tk()
root.withdraw()
# askyesno returns True (Yes) or False (No)
if msg.askyesno("Checkout", "Proceed with purchase?"):
print("Action: Order placed.")
else:
print("Action: Order cancelled.")
# askokcancel returns True (OK) or False (Cancel)
proceed = msg.askokcancel("Clear Data", "Delete all cached data?")
print("askokcancel returned:", proceed)
root.destroy()Terminal Output:
Action: Order placed.
askokcancel returned: True
import tkinter as tk
from tkinter import messagebox as msg
root = tk.Tk()
root.withdraw()
# askyesnocancel returns True (Yes), False (No), or None (Cancel/Esc)
decision = msg.askyesnocancel("Unsaved Work", "Save file before exit?")
if decision is True:
print("Action: Save and quit.")
elif decision is False:
print("Action: Discard and quit.")
else:
print("Action: Cancel. Keep editor open.")
root.destroy()Terminal Output:
Action: Save and quit.
import tkinter as tk
from tkinter import messagebox as msg
root = tk.Tk()
root.withdraw()
# default='no' pre-selects No; icon='warning' displays caution icon
safe_del = msg.askyesno("Delete User", "Permanently delete record?", default='no', icon='warning')
print("Deletion confirmed:", safe_del)
root.destroy()Terminal Output:
Deletion confirmed: False
import tkinter as tk
from tkinter import messagebox as msg
my_w = tk.Tk()
my_w.geometry("360x200")
my_w.title("Messagebox Response")
def show_msg():
res = msg.askyesnocancel('Prompt', 'Commit pending changes?')
print("User choice:", res)
l1.config(text=f"Response: {res}")
b1 = tk.Button(my_w, text='Open Dialog', command=show_msg, padx=10, pady=5)
b1.grid(row=1, column=1, padx=30, pady=20)
l1 = tk.Label(my_w, text='Awaiting Input', font=('Helvetica', 14, 'bold'), bg='yellow', padx=10)
l1.grid(row=2, column=1, padx=30)
# my_w.mainloop()Terminal Output:
User choice: True
Label Updated: Response: True
Protecting destructive database operations with defensive confirmation prompts:
def delete_guard(record_id: int, name: str) -> bool:
"""Protects database purges with a high-safety confirmation prompt."""
prompt = f"Delete record {record_id} ({name})?\nThis action is irreversible."
return msg.askyesno("Confirm Purge", prompt, icon='warning', default='no')
print("Purge status:", delete_guard(1042, "Alex Mercer"))Terminal Output:
Purge status: FalseIntercepting the window close protocol (WM_DELETE_WINDOW):
def setup_window_close_guard(app, is_dirty=True):
"""Intercepts standard window close (WM_DELETE_WINDOW) to guard unsaved edits."""
def on_closing():
if is_dirty:
res = msg.askyesnocancel("Unsaved Work", "Save changes before closing?")
if res is True:
print("Saving file to disk...")
app.destroy()
elif res is False:
print("Closing without saving...")
app.destroy()
else:
print("Close aborted.")
else:
app.destroy()
app.protocol("WM_DELETE_WINDOW", on_closing)Terminal Output:
Protocol callback successfully registered.
Practice modal dialog invocations, return-type inspections, and window protocol handlers in our interactive companion Jupyter Notebook:
Explore interactive code cells, simulate user dialog choices, benchmark default button configurations, and run self-validating assertions.
View on GitHub Run in Google ColabRun these unit checks directly in Python or your local environment to verify dialog logic:
def simulate(val):
return "YES" if val is True else ("NO" if val is False else "CANCEL")
assert simulate(True) == "YES"
assert simulate(False) == "NO"
assert simulate(None) == "CANCEL"
print("Messagebox dialog logic successfully verified!")Terminal Output:
Messagebox dialog logic successfully verified!
messagebox is a submodule of tkinter. Importing tkinter as tk does not automatically bind submodules into namespace, requiring from tkinter import messagebox.
Call root = tk.Tk(); root.withdraw() before calling your message box, then invoke root.destroy() afterwards.
askyesno() returns a boolean (True or False), while askquestion() returns string literals ('yes' or 'no').
Standard OS message boxes use fixed button labels. To create custom buttons, construct a custom modal using tk.Toplevel with custom Button widgets.
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.