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

(yzsuai) #1
C:\...\PP4E\Gui\Tools> python
>>> from tkinter import Tk
>>> from pipe_gui3 import redirectedGuiShellCmd
>>> root = Tk()
>>> redirectedGuiShellCmd('python -u spams.py', root)

Figure 10-16. Command pipe GUI displaying another program’s output


If the spawned program exits, Example 10-29’s producer thread detects end-of-file on
the pipe and puts a final empty line in the queue; in response the consumer loop displays
an line in the GUI by default when it detects this condition. In this case, program
exit is normal and silent; in other cases, we may need to add shutdown logic to suppress
error messages. Note that here again, the sleep call in the spawned program simulates
a long-running task, and we really need the -u unbuffered streams flag—without it, no
output appears in the GUI for eight seconds, until the spawned program is completely
finished. With it, the GUI receives and displays each line as it is printed, one every two
seconds.


This is also, finally, the sort of code you could use to display the output of a non-GUI
program in a GUI, without sockets, changes in the original program, or blocking the
GUI. Of course, in many cases, if you have to work this hard to add a GUI anyhow,
you might as well just make your script a traditional GUI program with a main window
and event loop. Furthermore, the GUIs we’ve coded in this section are limited to dis-
playing another program’s output; sometimes the GUI may have to do more. For many
programs, though, the general separation of display and program logic provided by the
spawned GUI model can be an advantage—it’s easier to understand both parts if they
are not mixed together.


We’ll learn more about sockets in the next part of the book, so you should consider
parts of this discussion something of a preview. As we’ll see, things start to become
more and more interesting when we start combining GUIs, threads, and network
sockets.


Before we do, though, the next chapter rounds out the purely GUI part of this book by
applying the widgets and techniques we’ve learned in more realistically scaled pro-
grams. And before that, the next section wraps up here with a preview of some of the


More Ways to Add GUIs to Non-GUI Code | 661
Free download pdf