Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 40 ยท Dialogs and Menus

Message Boxes: showinfo, askyesno and Friends

Learn Tkinter message boxes: show information, warnings and errors, ask yes/no or retry questions, read each return value and keep your code testable.

Almost every desktop program needs to talk to the user in a small pop-up window: "File saved", "Delete this item?", "Something went wrong". Tkinter ships ready-made versions of these windows in the tkinter.messagebox module. You do not build them yourself. You call one function, the window appears, the program waits, and the function returns what the user chose.

This lesson covers all of the message box functions, what each one returns, and how to avoid the classic mistakes (an extra empty window, comparing against the wrong value). Tkinter needs a screen, so the window code on this page is read-only. The runnable blocks use plain Python stand-ins that show the decision logic, which is the part you actually write and test.

Importing the module

messagebox is a submodule. import tkinter as tk does not import it, so you need a second import:

Python
import tkinter as tk
from tkinter import messagebox

root = tk.Tk()
root.withdraw()          # hide the empty main window (only for dialog-only scripts)
messagebox.showinfo("Saved", "Your file was saved.")
root.destroy()

A small window with an information icon, the title "Saved", the text "Your file was saved." and one OK button appears. The script continues after the user presses OK (or closes the window). If you never create a Tk() first, Tkinter creates a hidden default root for you and a stray blank window may show up, which is why scripts that only show dialogs call root.withdraw().

The three "show" functions

These only inform; they return the string "ok" and you normally ignore it.

Function Icon Use it for
showinfo(title, message) blue "i" Neutral news: saved, done, copied
showwarning(title, message) yellow triangle Something is odd but the program continues
showerror(title, message) red cross An operation failed
Python
from tkinter import messagebox

try:
    value = int(entry.get())
except ValueError:
    messagebox.showerror("Invalid number", "Please type digits only.")

Keep the title short (it is the window caption) and make the message tell the user what to do next, not only what went wrong.

The "ask" functions and their return values

The question dialogs return something you act on. The return types differ, and this is where most bugs hide.

Function Buttons Returns
askokcancel OK, Cancel True / False
askyesno Yes, No True / False
askretrycancel Retry, Cancel True / False
askyesnocancel Yes, No, Cancel True / False / None
askquestion Yes, No the strings "yes" / "no"

Two details are worth memorizing. First, askquestion returns strings, so if messagebox.askquestion(...) is always true because "no" is a non-empty string. Prefer askyesno. Second, askyesnocancel returns None for Cancel, so if answer: cannot tell "No" from "Cancel". Compare with is None first.

Python
answer = messagebox.askyesnocancel("Quit", "Save changes before closing?")
if answer is None:
    pass                    # Cancel: stay in the program
elif answer:
    save_file()
    root.destroy()
else:
    root.destroy()          # No: discard

Options: icon, default button, parent

All of these functions accept keyword arguments:

Python
messagebox.askyesno(
    "Delete",
    "Delete 12 files permanently?",
    icon="warning",            # "info", "warning", "error" or "question"
    default="no",              # the button that Enter presses
    parent=settings_window,    # the dialog is centered on and tied to this window
)

Always pass parent= when your program has more than one window. Without it, the dialog can open behind the window it belongs to or on a different place of the screen, and on some systems the main window stays clickable. Choose a safe default for destructive questions: default="no" means a nervous Enter key press does not delete anything.

Message boxes are modal: they block the line of code that called them, but Tkinter keeps running its own event loop inside the call. Timers created with after still fire while the dialog is open.

Making the logic testable

Dialog calls are awkward to test because a human has to press a button. The trick is to keep the decision logic in a function that receives the "ask" function as a parameter. In the real program you pass messagebox.askyesno; in a test you pass a stand-in that returns what you want.

The block below is not Tkinter. It models the return values of the dialog family and a delete routine that works with any asker.

Python Stand-in: dialog return values and an injectable asker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The same function works in the real app with delete_files(files, messagebox.askyesno). In the next block a quit routine handles the three-way askyesnocancel result, including the None trap.

Python Stand-in: the three-way quit question

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Other dialogs that look like message boxes

Tkinter also has dialogs that return typed data: simpledialog.askstring, askinteger, askfloat, file pickers and the color chooser. They are covered in File Dialogs, Color Chooser and simpledialog. If you need a form with several fields, build your own window as shown in Toplevel Windows and Custom Dialogs.

Common mistakes

  • Forgetting from tkinter import messagebox. You get AttributeError: module 'tkinter' has no attribute 'messagebox'.
  • Using askquestion in an if. Use askyesno.
  • Showing an error dialog in a loop. One dialog per failed row is a wall of pop-ups; collect problems and show one message.
  • Calling a dialog from a background thread. Tkinter is not thread-safe; hand the message to the main thread instead (see Threads and Background Work).
  • Very long messages. A dialog is for one or two sentences; use a Toplevel with a Text widget for logs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does messagebox.askyesno return when the user presses No?

    askyesno returns a real boolean: True for Yes, False for No. Only askquestion returns strings.
  2. 2. Why is if messagebox.askquestion(...) a bug?

    Any non-empty string is truthy in Python, so the condition is true even when the user pressed No. Use askyesno or compare with == 'yes'.
  3. 3. How do you tell Cancel apart from No with askyesnocancel?

    Yes is True, No is False and Cancel is None, so check for None first.
  4. 4. Why pass parent=window to a message box?

    With several windows, parent= keeps the dialog above the right window and blocks only that one.

Summary

  • showinfo, showwarning and showerror inform and return "ok".
  • askyesno, askokcancel and askretrycancel return booleans; askyesnocancel can return None; askquestion returns strings.
  • Pass parent= with several windows and default="no" for dangerous questions.
  • Import tkinter.messagebox explicitly.
  • Pass the "ask" function into your logic so it can be tested without a human.

Next: File Dialogs, Color Chooser and simpledialog