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

(yzsuai) #1

from tkinter import *
import canvasDraw_tags
import _thread, time


class CanvasEventsDemo(canvasDraw_tags.CanvasEventsDemo):
def moveEm(self, tag):
for i in range(5):
for (diffx, diffy) in [(+20, 0), (0, +20), (−20, 0), (0, −20)]:
self.canvas.move(tag, diffx, diffy)
time.sleep(0.25) # pause this thread only


def moveInSquares(self, tag):
_thread.start_new_thread(self.moveEm, (tag,))


if name == 'main':
CanvasEventsDemo()
mainloop()


This version lets you move shapes at the same time, just like Example 9-31, but this
time it’s a reflection of threads running in parallel. In fact, this uses the same scheme
as the first time.sleep version. Here, though, there is more than one active thread of
control, so move handlers can overlap in time—time.sleep blocks only the calling
thread, not the program at large.


This example works on Windows today, but it failed on Linux at one point in this
book’s lifetime—the screen was not updated as threads changed it, so you couldn’t see
any changes until later GUI events. The usual rule of thumb about avoiding GUI up-
dates in spawned threads laid out earlier still holds true. It is usually safer to have your
threads do number crunching only and let the main thread (the one that built the GUI)
handle any screen updates. Even under this model, though, the main thread can still
use after event loops like that of Example 9-31 to watch for results from worker threads
to appear without being blocked while waiting (more on this in the next section and
chapter).


Parts of this story are implementation details prone to change over time, and it’s not
impossible that GUI updates in threads may be better supported by tkinter in the future,
so be sure to explore the state of threading in future releases for more details.


Other Animation Topics


We’ll revisit animation in Chapter 11’s PyDraw example; there, all three of the tech-
niques we just met—sleeps, timers, and threads—will be resurrected to move shapes,
text, and photos to arbitrary spots on a canvas marked with a mouse click. And although
the canvas widget’s absolute coordinate system makes it the workhorse of most non-
trivial animations, tkinter animation in general is limited mostly by your imagination.
In closing, here are a few more words on the topic to hint at the possibilities.


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