Getting Started with Events and Animations (Tkinter)
- Event-Based Programming (Model-View-Controller)
- Event handlers (mousePressed, keyPressed, timerFired), or controllers, wait to be called
- When called, event handlers modify the model by changing canvas.data
- Then, event event handlers modify the view by calling redrawAll
- Elements of an Event-Based Program
- run()
- written for you (so you just copy-paste from code provided for you)
- creates canvas and canvas.data; registers event handlers; calls init; starts timer; etc
- You call run() to start program
- init()
- initialize values in canvas.data
- mousePressed(event)
- extract mouse location via event.x, event.y
- modify canvas.data based on mouse press location
- call redrawAll if view changed
- keyPressed(event)
- extract char and/or keysym from event.char and event.keysym
- modify canvas.data based on key pressed
- call redrawAll if view changed
- timerFired()
- modify canvas.data based on elapsed time
- call redrawAll if view changed
- call canvas.after() to schedule next timerFired event (after a delay of your choice)
- redrawAll()
- clear the canvas with canvas.delete(ALL)
- redraw all canvas elements from back to front based on values in canvas.data
- 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)
- More Reading (mostly for the brave at heart)
- http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm
- http://docs.python.org/library/tkinter.html#bindings-and-events