July 2002
Intermediate to advanced
608 pages
15h 46m
English
Credit: Jacob Hallén
You need to access sockets, serial ports, and do other asynchronous (but blocking) I/O while running a Tkinter-based GUI.
The solution is to handle a Tkinter interface on one thread and
communicate to it (via Queue objects) the events
on I/O channels handled by other threads:
import Tkinter
import time
import threading
import random
import Queue
class GuiPart:
def _ _init_ _(self, master, queue, endCommand):
self.queue = queue
# Set up the GUI
console = Tkinter.Button(master, text='Done', command=endCommand)
console.pack( )
# Add more GUI stuff here depending on your specific needs
def processIncoming(self):
"""Handle all messages currently in the queue, if any."""
while self.queue.qsize( ):
try:
msg = self.queue.get(0) # Check contents of message and do whatever is needed. As a # simple test, print it (in real life, you would # suitably update the GUI's display in a richer fashion). print msg except Queue.Empty: # just on general principles, although we don't # expect this branch to be taken in this case pass class ThreadedClient: """ Launch the main part of the GUI and the worker thread. periodicCall and endApplication could reside in the GUI part, but putting them here means that you have all the thread controls in a single place. """ def _ _init_ _(self, master): """ Start the GUI and the asynchronous threads. We are in the main (original) thread of the application, which will later be used ...Read now
Unlock full access