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

(yzsuai) #1

for i in range(self.reps): # access to object state here
time.sleep(1)
if progress: progress(i) # progress callback: queued
if id % 2 == 1: raise Exception # odd numbered: fail


thread callbacks: dispatched off queue in main thread


def threadexit(self, myname):
self.text.insert('end', '%s\texit\n' % myname)
self.text.see('end')


def threadfail(self, exc_info, myname): # have access to self state
self.text.insert('end', '%s\tfail\t%s\n' % (myname, exc_info[0]))
self.text.see('end')


def threadprogress(self, count, myname):
self.text.insert('end', '%s\tprog\t%s\n' % (myname, count))
self.text.see('end')
self.text.update() # works here: run in main thread


if name == 'main': MyGUI().text.mainloop()


This code both queues bound methods as thread exit and progress actions and runs
bound methods as the thread’s main action itself. As we learned in Chapter 5, because
threads all run in the same process and memory space, bound methods reference the
original in-process instance object, not a copy of it. This allows them to update the GUI
and other implementation state directly. Furthermore, because bound methods are
normal objects which pass for callables interchangeably with simple functions, using
them both on queues and in threads this way just works. To many, this broadly shared
state of threads is one of their primary advantages over processes.


Watch for the more realistic application of this module in Chapter 14’s PyMailGUI,
where it will serve as the core thread exit and progress dispatch engine. There, we’ll
also run bound methods as thread actions, too, allowing both threads and their queued
actions to access shared mutable object state of the GUI. As we’ll see, queued action
updates are automatically made thread-safe by this module’s protocol, because they
run in the main thread only. Other state updates to shared objects performed in
spawned threads, though, may still have to be synchronized separately if they might
overlap with other threads, and are made outside the scope of the callback queue. A
direct update to a mail cache, for instance, might lock out other operations until
finished.


More Ways to Add GUIs to Non-GUI Code


Sometimes, GUIs pop up quite unexpectedly. Perhaps you haven’t learned GUI pro-
gramming yet; or perhaps you’re just pining for non-event-driven days past. But for
whatever reason, you may have written a program to interact with a user in an inter-
active console, only to decide later that interaction in a real GUI would be much nicer.
What to do?


646 | Chapter 10: GUI Coding Techniques

Free download pdf