CMU 15-112: Fundamentals of Programming and Computer Science
Class Notes: Event-Based Animations in Tkinter
Note: We will only run animations in Standard Python. These examples will not run in Brython.
- Event-Based Programming (Model-View-Controller or MVC)
- Tkinter owns the event loop. Your code does nothing until it is called, then it runs quickly and returns control back to Tkinter.
- When a mouse, keyboard, or timer event occurs, Tkinter calls the appropriate event handler function (mousePressed, keyPressed, timerFired), or controller, that you wrote.
- When called from Tkinter, your controllers modify the model (the values in data).
- Soon after that, Tkinter updates the view by calling your function redrawAll, which redraws the canvas (the view) based on the model (the values in data.xyz)
- Elements of Event-Based Animations
- run(width, height)
written for you (so you just copy-paste from code provided for you) creates canvas and data; registers event handlers; calls init; starts timer; etc You call run() to start program - init(data)
initialize values in data - mousePressed(event, data)
extract mouse location via event.x, event.y; modify data based on mouse press location - keyPressed(event, data)
extract char and/or keysym from event.char and event.keysym; modify data based on key pressed - timerFired(data)
modify data based on elapsed time - redrawAll(canvas, data)
redraw all canvas elements from back to front based on values in data
- run(width, height)
- Examples
- events-example0.py (barebones)
- events-example1.py (with simple counter, and displaying text describing events)
- events-example2.py (responding to events by creating, deleting, and changing graphics)
- events-example3.py (this time with a bouncing, pausing square)
- Worked Examples