liveBook · Manning

Handler

As explained in Get Programming: Learn to code with Python

An event handler is a function or code unit that runs in response to an interaction or other event generated by a user-interface component.

An event handler is a function that runs when a user interacts with a graphical-user-interface widget or when another event occurs. A button can connect to a function that changes the window, while a canvas can connect keypresses to movement commands. section 37.1 section 37.4

An event handler usually follows this pattern:

  • Define a function containing the response. section 37.4
  • Link the widget or event to that function. section 37.4
  • Read any needed input, perform the action, and update the interface. section 37.4

A button handler

def change_color(): window.configure(background="white") white = tkinter.Button(window, text="Click", command=change_color) When the user clicks the button, tkinter calls change_color. The function changes the window background from gray to white. The function name is passed as the command; it is not called while the button is being created. section 37.4

Handling keyboard input

A canvas can send keypress events to one handler. The handler checks event.char and tells the appropriate Player object which direction to move. This keeps input decisions in the handler while reusable movement logic stays inside the Player class. section 38.3

Listing 37.3. Event handler for a button click
import tkinter

def change_color():                                                    #1
    window.configure(background="white")                               #2

window = tkinter.Tk()
window.geometry("800x200")
window.title("My first GUI")
window.configure(background="grey")

white = tkinter.Button(window, text="Click", command=change_color)     #3
white.pack()

window.mainloop()

Browse the complete tkinter example showing the function, button configuration, and connection between a click and its response. section 37.4

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains definition, widget linkage, input reading, interface updates, and modular dispatch, but not event-system internals.
Examples
Demonstrates a button changing a window color, a countdown timer, and a two-player canvas game controlled by keypresses.
What you can do after
Build it from scratch by connecting tkinter widgets and canvas events to functions that update a GUI.
How it connects
Connects event handlers with GUI widgets, functions, loops, classes, canvases, and libraries.

Also explained in

Compare how 21 books explain handler →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.