15-110 Lecture Topics:  Events and Animations

Week #8  Oct 11 – Oct 15

  1. Event-Based Programming
    1. Flow of Control (passively waiting, not actively polling)
    2. Accessing data in callbacks (via the canvas.data dictionary)
    3. Finding the canvas in callbacks (via the "widget" parameter)
  2. Elements of an Event-Based Program
    1. run()
      1. written for you (so you just copy-paste from code provided for you)
      2. creates canvas and canvas.data; registers event handlers; calls init; starts timer; etc
      3. call run() to start program
    2. init(canvas)
      1. initialize values in canvas.data
    3. mousePressed(event)
      1. extract mouse location via event.x, event.y
      2. modify canvas.data based on mouse press location
      3. call redrawAll if view changed
    4. keyPressed(event)
      1. extract char and/or keysym from event.char and event.keysym
      2. modify canvas.data based on key pressed
      3. call redrawAll if view changed
    5. timerFired(canvas)
      1. modify canvas.data based on elapsed time
      2. call redrawAll if view changed
      3. call canvas.after() to schedule next timerFired event (after a delay of your choice)
    6. redrawAll(canvas)
      1. clear the canvas with canvas.delete(ALL)
      2. redraw all canvas elements from back to front based on values in canvas.data
  3. Examples
    1. events-example0.py (barebones)
    2. events-example1.py (with simple counter, and displaying text describing events)
    3. events-example2.py (responding to events by creating, deleting, and changing graphics)
    4. events-example3.py (this time with a bouncing square)
  4. Recommended Reading
    1. http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm
    2. http://docs.python.org/library/tkinter.html#bindings-and-events