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

(yzsuai) #1

Recoding with classes and bound methods


Example 10-19 takes the model one small step further and migrates it to a class to allow
for future customization and reuse. Its operation, window, and output are the same as
the prior non-object-oriented version, but the queue is checked more often, and there
are no standard output prints. Notice how we use bound methods for button callbacks
and thread actions here; because bound methods retain both instance and method, the
threaded action has access to state information, including the shared queue. This allows
us to move the queue and the window itself from the prior version’s global variables to
instance object state.


Example 10-19. PP4E\Gui\Tools\queuetest-gui-class.py


GUI that displays data produced and queued by worker threads (class-based)


import threading, queue, time
from tkinter.scrolledtext import ScrolledText # or PP4E.Gui.Tour.scrolledtext


class ThreadGui(ScrolledText):
threadsPerClick = 4


def init(self, parent=None):
ScrolledText.init(self, parent)
self.pack()
self.dataQueue = queue.Queue() # infinite size
self.bind('', self.makethreads) # on left mouse click
self.consumer() # queue loop in main thread


Figure 10-11. Display updated by main GUI thread


638 | Chapter 10: GUI Coding Techniques

Free download pdf