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.
  1. Event-Based Programming (Model-View-Controller or MVC)
    1. Tkinter owns the event loop. Your code does nothing until it is called, then it runs quickly and returns control back to Tkinter.
    2. When a mouse, keyboard, or timer event occurs, Tkinter calls the appropriate event handler function (mousePressed, keyPressed, timerFired), or controller, that you wrote.
    3. When called from Tkinter, your controllers modify the model (the values in data).
    4. 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)

  2. Elements of Event-Based Animations
    1. 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
    2. init(data)
      initialize values in data
    3. mousePressed(event, data)
      extract mouse location via event.x, event.y; modify data based on mouse press location
    4. keyPressed(event, data)
      extract char and/or keysym from event.char and event.keysym; modify data based on key pressed
    5. timerFired(data)
      modify data based on elapsed time
    6. redrawAll(canvas, data)
      redraw all canvas elements from back to front based on values in 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, pausing square)
    5. Worked Examples
      1. Mode Demo
      2. Grid Demo
      3. Undo/Redo Demo
      4. Images Demo
      5. Snake Demo
      6. Side Scroller Demo
      7. Tetris