Example 9-31. PP4E\Gui\Tour\canvasDraw_tags_after.py
"""
similar, but with widget.after() scheduled events, not time.sleep loops;
because these are scheduled events, this allows both ovals and rectangles
to be moving at the same time and does not require update calls to refresh
the GUI; the motion gets wild if you press 'o' or 'r' while move in progress:
multiple move updates start firing around the same time;
"""
from tkinter import *
import canvasDraw_tags
class CanvasEventsDemo(canvasDraw_tags.CanvasEventsDemo):
def moveEm(self, tag, moremoves):
(diffx, diffy), moremoves = moremoves[0], moremoves[1:]
self.canvas.move(tag, diffx, diffy)
if moremoves:
self.canvas.after(250, self.moveEm, tag, moremoves)
def moveInSquares(self, tag):
allmoves = [(+20, 0), (0, +20), (−20, 0), (0, −20)] * 5
self.moveEm(tag, allmoves)
if name == 'main':
CanvasEventsDemo()
mainloop()
This version inherits the drawing customizations of the prior, but lets you make both
ovals and rectangles move at the same time—drag out a few ovals and rectangles, and
then press “o” and then “r” right away to make this go. In fact, try pressing both keys
a few times; the more you press, the more the objects move, because multiple scheduled
events are firing and moving objects from wherever they happen to be positioned. If
you drag out a new shape during a move, it starts moving immediately as before.
Using multiple time.sleep loop threads
Running animations in threads can sometimes achieve the same effect. As discussed
earlier, it can be dangerous to update the screen from a spawned thread in general, but
it works in this example (on the test platform used, at least). Example 9-32 runs each
animation task as an independent and parallel thread. That is, each time you press the
“o” or “r” key to start an animation, a new thread is spawned to do the work.
Example 9-32. PP4E\Gui\Tour\canvasDraw_tags_thread.py
"""
similar, but run time.sleep loops in parallel with threads, not after() events
or single active time.sleep loop; because threads run in parallel, this also
allows ovals and rectangles to be moving at the same time and does not require
update calls to refresh the GUI: in fact, calling .update() once made this crash
badly, though some canvas calls must be thread safe or this wouldn't work at all;
"""
592 | Chapter 9: A tkinter Tour, Part 2