tkinter and CustomTkinter · lesson 6 of 8
Parts in this lesson
Abind("<Return>", ...)any event
Bmessagebox.showwarninga ready-made dialog
Cprotocol("WM_DELETE_WINDOW", ...)when the window closes
Droot.after(3000, saved)later, without waiting

Events, refusals and closing

Last updated

Buttons aren't the only things that happen in a window: keys are pressed, rows are double-clicked, and the window is closed. In this lesson you'll bind code to any event, show the presenter's refusals in a dialog, ask before the window closes, and see why a slow handler freezes the whole window.

By the end of this lesson you can

  • Bind a method to a key or mouse event, and read the event object
  • Show a refusal with messagebox
  • Run code when the user closes the window
  • Explain why a slow handler freezes the window, and wait with after instead

Refusals in a dialog

Lesson T.4's presenter turns every refusal into a Message with ok=False. The window's job is to show it. The reference puts every message in the status line, and a refusal in a dialog too, so it can't be missed:

How the reference does it library_gui/tk_app.py, lines 69–81
    def lend(self) -> None:
        member_id = self.names.get(self.member.get(), "")
        self.show(self.presenter.lend(self.chosen_item(), member_id))

    def give_back(self) -> None:
        self.show(self.presenter.give_back(self.chosen_item()))

    def show(self, message: Message) -> None:
        self.status.set(message.text)
        if not message.ok:
            messagebox.showwarning("Library", message.text, parent=self)
        self.refresh()

messagebox.showwarning(title, text) opens a small dialog with an OK button and a warning icon, and waits until it's closed. parent=self keeps it over the window. The module has others: showinfo, showerror, and ones that ask, like askyesno and askokcancel, which return True or False.

lend and give_back are two lines each: get what's selected, hand it to the presenter, show the answer. That's all a view should do.

Keys, clicks and the event object

command= covers a button's click. For anything else, use bind: it ties a method to an event on one widget. Events are named in angle brackets:

EventWhen
"<Return>"the Enter key is pressed
"<Button-1>"the left mouse button is pressed
"<Double-1>"the left button is double-clicked
"<KeyPress>"any key is pressed

The reference lends an item when its row is double-clicked:

How the reference does it library_gui/tk_app.py, lines 42–42
        self.table.bind("<Double-1>", lambda event: self.lend())

A bound method is called with one argument, an event object, with what happened: event.x and event.y for where the mouse was, event.keysym for which key, event.widget for which widget. lend doesn't take one, so a lambda (lesson 2.5) takes the event and ignores it.

This window binds Enter in a search box. Save it as close.py and run it, type something, and press Enter:

import tkinter as tk
from tkinter import messagebox, ttk

root = tk.Tk()
root.title("Library desk")
search = ttk.Entry(root)
search.pack(padx=20, pady=20)


def searched(event: tk.Event) -> None:
    print(f"Search for {search.get()!r}")


def ask_to_close() -> None:
    if messagebox.askokcancel("Library desk", "Close the library desk?", parent=root):
        root.destroy()


search.bind("<Return>", searched)
root.protocol("WM_DELETE_WINDOW", ask_to_close)
root.mainloop()

searched is called with the event, and reads the box. Then close the window with its title bar's close button.

Ask before closing

When you closed the window in step 2, it asked first. That's the second-to-last line:

root.protocol("WM_DELETE_WINDOW", ask_to_close)

WM_DELETE_WINDOW is the message the system sends when the user closes a window. Normally tkinter just destroys the window. With protocol, your method is called instead, and the window closes only if it calls root.destroy().

The reference doesn't need to ask, because the presenter saves after every change. A program that saves only when it closes would save here: this is where the capstone's menu saved on quit.

ask_to_close returns without calling root.destroy(). What happens to the window?

A slow handler

The wrong way. Some jobs take a while: saving to a slow network drive, say. Here's a pretend one, with time.sleep(3). Save it as slow.py, run it, press Save, and then try to move the window:

import time
import tkinter as tk
from tkinter import ttk

root = tk.Tk()
status = ttk.Label(root, text="Ready")
status.pack(padx=40, pady=10)


def save_slowly() -> None:
    status.configure(text="Saving...")
    time.sleep(3)  # pretend saving takes three seconds
    status.configure(text="Saved.")


ttk.Button(root, text="Save", command=save_slowly).pack(pady=(0, 20))
root.mainloop()

For three seconds the window is frozen. It won't move or redraw, and on some systems its title says Not Responding. And the label never shows Saving...: it goes straight from Ready to Saved..

Why? There's one event loop, and it runs one thing at a time. While save_slowly sleeps, the loop is stuck inside it, so it can't redraw the label, move the window, or handle anything else. The label is only redrawn once the handler returns, and by then it says Saved..

So a handler must return quickly. To do something later, ask the loop to call you later:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
status = ttk.Label(root, text="Ready")
status.pack(padx=40, pady=10)


def save_slowly() -> None:
    status.configure(text="Saving...")
    root.after(3000, saved)  # call saved() in 3000 ms, and return now


def saved() -> None:
    status.configure(text="Saved.")


ttk.Button(root, text="Save", command=save_slowly).pack(pady=(0, 20))
root.mainloop()

root.after(3000, saved) returns at once. The loop carries on handling events, and calls saved after 3000 milliseconds. Now Saving... shows, and the window can move.

after is for waiting. Real slow work, like a big download, needs a thread, a second line of work running beside the loop, which is beyond this module. The rule stays the same: never make the event loop wait.

Check

What argument does a method bound with bind get?
A button's handler calls time.sleep(3). Why does the window freeze?
How do you run saved in three seconds without freezing the window?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Python