Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 40 ยท Dialogs and Menus

Toplevel Windows and Custom Dialogs in Tkinter

Open extra windows with Tkinter Toplevel, make them modal with grab_set and wait_window, return values from a custom dialog and close them safely.

The ready-made dialogs cover simple questions. Sooner or later you need your own: a Settings window, a form with three fields and a combo box, an "About" box with a logo, a find-and-replace panel. In Tkinter, every window after the first is a Toplevel, and a custom dialog is a Toplevel with a few extra rules.

This lesson explains how to open and close windows, how to make a dialog modal (the user must finish it first), and the pattern for returning a value to the caller. The Tkinter code is read-only; runnable blocks model the life cycle and the return-value flow in plain Python.

One root, many Toplevels

A program has exactly one Tk() object, the root window. Closing the root ends the program. Extra windows are Toplevel(parent):

Python
import tkinter as tk

root = tk.Tk()
root.title("Main")

def open_about():
    win = tk.Toplevel(root)
    win.title("About")
    win.geometry("280x140")
    win.resizable(False, False)
    tk.Label(win, text="Notes 1.0\nA tiny editor", pady=16).pack()
    tk.Button(win, text="Close", command=win.destroy).pack()

tk.Button(root, text="About", command=open_about).pack(padx=40, pady=40)
root.mainloop()

Pressing the "About" button opens a second, small, fixed-size window with two lines of text and a Close button. The main window stays usable. Pressing About twice opens two windows, which is usually not what you want; keep a reference and reuse it (see below).

Important window methods, all available on Tk and Toplevel:

Method Effect
title("text") caption
geometry("300x200+100+80") size and position (width x height + x + y)
resizable(False, False) fixed size
minsize(w, h) / maxsize(w, h) limits
iconbitmap(...) / iconphoto(...) window icon
attributes("-topmost", True) keep above others
transient(parent) tie to a parent: shown above it, no separate taskbar entry on most systems
withdraw() / deiconify() hide / show
destroy() close and delete the window and all of its children
protocol("WM_DELETE_WINDOW", func) run func when the user presses the close button

withdraw hides a window but keeps it, destroy removes it. After destroy, calling any method on the window raises TclError: bad window path name.

Intercepting the close button

Python
def on_close():
    if messagebox.askyesno("Quit", "Close the settings window?", parent=win):
        win.destroy()

win.protocol("WM_DELETE_WINDOW", on_close)

Now the title bar's X asks first. The same protocol on the root window is where you save settings before the program exits.

Making a dialog modal

A modal dialog blocks interaction with other windows until it closes. Tkinter does this with three calls:

Python
dialog.transient(parent)     # stay on top of the parent
dialog.grab_set()            # all mouse and keyboard input goes to the dialog
parent.wait_window(dialog)   # pause THIS function until the dialog is destroyed

grab_set() redirects events to the dialog. wait_window() runs a nested event loop, so the rest of the program (timers, redraws) continues to work, while the function that opened the dialog stays suspended on that line and continues after the dialog closes. This is exactly how messagebox behaves, which is why askyesno can return a value in the middle of a function.

Call grab_set() only after the window is visible. On some Linux window managers it fails with TclError: grab failed: window not viewable. Calling dialog.wait_visibility() first fixes it.

A reusable dialog class that returns a value

The pattern: store the result in an attribute, destroy the window, and let the caller read the attribute after wait_window returns.

Python
import tkinter as tk
from tkinter import ttk

class AskNameDialog(tk.Toplevel):
    def __init__(self, parent, title="Your name", initial=""):
        super().__init__(parent)
        self.title(title)
        self.transient(parent)
        self.resizable(False, False)
        self.result = None                       # None means Cancel

        self.var = tk.StringVar(value=initial)
        frame = ttk.Frame(self, padding=14)
        frame.grid()
        ttk.Label(frame, text="Name:").grid(row=0, column=0, sticky="w")
        entry = ttk.Entry(frame, textvariable=self.var, width=24)
        entry.grid(row=0, column=1, padx=(8, 0))
        buttons = ttk.Frame(frame)
        buttons.grid(row=1, column=0, columnspan=2, pady=(12, 0), sticky="e")
        ttk.Button(buttons, text="OK", command=self.ok).pack(side="left")
        ttk.Button(buttons, text="Cancel", command=self.cancel).pack(side="left", padx=(6, 0))

        self.bind("<Return>", lambda e: self.ok())
        self.bind("<Escape>", lambda e: self.cancel())
        self.protocol("WM_DELETE_WINDOW", self.cancel)

        entry.focus_set()
        self.wait_visibility()
        self.grab_set()
        parent.wait_window(self)                 # blocks here

    def ok(self):
        self.result = self.var.get().strip()
        self.destroy()

    def cancel(self):
        self.result = None
        self.destroy()

# caller
name = AskNameDialog(root).result
if name:
    print("Hello,", name)

A small window appears with a label, a text box, OK and Cancel. Enter confirms, Escape cancels, and the X button counts as Cancel. The constructor does not return until the dialog is closed, so AskNameDialog(root).result already holds the answer. That is not elegant object design, but it mirrors askstring and is common in real programs. A cleaner variant is a function ask_name(parent) that builds the dialog, waits and returns dialog.result.

Good dialogs share a few habits: focus on the first field, Enter for OK, Escape for Cancel, a clear Cancel result (None), and validation before closing: if the name is empty, show a message and keep the dialog open.

Keeping only one window

To avoid duplicates, store the window and check it:

Python
class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.settings_win = None

    def open_settings(self):
        if self.settings_win is not None and self.settings_win.winfo_exists():
            self.settings_win.lift()
            self.settings_win.focus_force()
            return
        self.settings_win = SettingsWindow(self)

winfo_exists() is true while the window is alive. lift() raises the existing window instead of creating a second one.

Modeling the life cycle

The block below is not Tkinter. It models a window that can be created, shown, hidden and destroyed, and a modal dialog whose result is read after "wait". It shows why using a destroyed window fails and why None means Cancel.

Python Stand-in: window life cycle and dialog results

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.

A form dialog with validation

Validation should keep the dialog open until the input is acceptable. The logic is independent of widgets, so you can test it on its own:

Python Stand-in: validating a dialog form

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.

In the real dialog, on_ok would call messagebox.showerror(parent=self, ...) and return without destroying the window.

Common mistakes

  • Creating a second Tk() for another window. Use Toplevel; two roots cause confusing image and variable bugs.
  • Forgetting parent.wait_window(dialog): the function returns at once, before the user answered, with result still None.
  • Using a variable after destroy() without saving the value first. Read the entry text before destroying.
  • Not handling the close button; the result stays at its default and the caller treats it as Cancel by accident or crashes.
  • Creating widgets in Toplevel with the wrong master (tk.Label(root, ...)): they appear in the main window.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which call makes a Toplevel modal and pauses the caller until it closes?

    grab_set redirects input to the dialog; wait_window suspends the calling function until the dialog is destroyed while the event loop keeps running.
  2. 2. What is the difference between withdraw() and destroy()?

    A withdrawn window can be shown again with deiconify(); a destroyed one cannot be used any more.
  3. 3. How should a custom dialog report that the user pressed Cancel?

    Initialize result to None, set it only in OK, and the caller can test the result like for askstring.
  4. 4. Why use Toplevel instead of a second Tk()?

    Multiple roots create separate Tcl interpreters, so variables and images do not work across them.

Summary

  • Extra windows are Toplevel(parent); the root Tk() is unique.
  • Use protocol("WM_DELETE_WINDOW", ...) to intercept the close button.
  • Modal dialogs use transient, grab_set and wait_window.
  • Store the dialog result in an attribute (None = Cancel); validate before closing.
  • Keep a reference and use winfo_exists() to avoid duplicate windows.

Next: Canvas: Shapes and Text