15-110
Lecture Topics: Events and Animations
Week
#8 Oct 11 – Oct 15
- Event-Based Programming
- Flow of Control (passively waiting, not actively polling)
- Accessing data in callbacks (via the canvas.data dictionary)
- Finding the canvas in callbacks (via the "widget" parameter)
- 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
- call run() to start program
- init(canvas)
- 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(canvas)
- 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(canvas)
- 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 square)
- Recommended Reading
- http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm
- http://docs.python.org/library/tkinter.html#bindings-and-events