15-112 Fundamentals of Programming

Notes - Lecture 4.1


Introduction to Event-Based Programming and Animations in Tkinter

Notes taken from here.

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 dictionary).
  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).

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(event, data)
    modify data based on elapsed time
  6. redrawAll(canvas, data)
    redraw everything that needs to be drawn on the canvas using the values stored in data

Examples

  • Barebones
  • Basic timer, mouse, keyboard events
  • One box falling
  • Multiple objects on screen
  • Raining circles
  • A more sophisticated example


  • Valid CSS! Valid XHTML 1.0 Strict