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




















