[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

Figure 9-42. Drag-out objects ready to be animated


Using widget.after events


The main drawback of this first approach is that only one animation can be going at
once: if you press “r” or “o” while a move is in progress, the new request puts the prior
movement on hold until it finishes because each move callback handler assumes the
only thread of control while it runs. That is, only one time.sleep loop callback can be
running at a time, and a new one started by an update call is effectively a recursive call
which pauses another loop already in progress.


Screen updates are a bit sluggish while moves are in progress, too, because they happen
only as often as manual update calls are made (try a drag-out or a cover/uncover of the
window during a move to see for yourself). In fact, uncommenting the canvas update
call in Example 9-30 makes the GUI completely unresponsive during the move—it
won’t redraw itself if covered, doesn’t respond to new user requests, and doesn’t show
any of its progress (you only get to see the final state). This effectively simulates the
impact of long-running operations on GUIs in general.


Example 9-31 specializes just the moveInSquares method of the prior example to remove
all such limitations—by using after timer callback loops, it schedules moves without
potential pauses. It also reflects the most common (and likely best) way that tkinter
GUIs handle time-based events at large. By breaking tasks into parts this way instead
of running them all at once, they are naturally both distributed over time and
overlapped.


Time Tools, Threads, and Animation | 591
Free download pdf