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

(yzsuai) #1

they won’t return to the GUI’s event loop until the function or shell command exits.
Although GuiOutput takes care to call tkinter’s update method to update the display
after each line is written, this module has no control in general over the duration of
functions or shell commands it runs.


In redirectedGuiShellCmd, for example, the call to input.readline will pause until an
output line is received from the spawned program, rendering the GUI unresponsive.
Because the output object runs an update call, the display is still updated during the
program’s execution (an update call enters the Tk event loop momentarily), but only
as often as lines are received from the spawned program. In addition, because of this
function’s loop, the GUI is committed to the shell command in general until it exits.


Calls to a redirected function in redirectedGuiFunc are similarly blocking in general;
moreover, during the call’s duration the display is updated only as often as the function
issues output requests. In other words, this blocking model is simplistic and might be
an issue in a larger GUI. We’ll revisit this later in the chapter when we meet threads.
For now, the code suits our present purpose.


Using Redirection for the Packing Scripts


Now, finally, to use such redirection tools to map command-line script output back to
a GUI, we simply run calls and command lines with the two redirected functions in
this module. Example 10-13 shows one way to wrap the packing operation dialog of
the shell GUI section’s Example 10-10 to force its printed output to appear in a pop-
up window when generated, instead of in the console.


Example 10-13. PP4E\Gui\ShellGui\packdlg-redirect.py


wrap command-line script in GUI redirection tool to pop up its output


from tkinter import *
from packdlg import runPackDialog
from PP4E.Gui.Tools.guiStreams import redirectedGuiFunc


def runPackDialog_Wrapped(): # callback to run in mytools.py
redirectedGuiFunc(runPackDialog) # wrap entire callback handler


if name == 'main':
root = Tk()
Button(root, text='pop', command=runPackDialog_Wrapped).pack(fill=X)
root.mainloop()


You can run this script directly to test its effect, without bringing up the ShellGui
window. Figure 10-9 shows the resulting stdout window after the pack input dialog is
dismissed. This window pops up as soon as script output is generated, and it is a bit
more GUI user friendly than hunting for messages in a console. You can similarly code
the unpack parameters dialog to route its output to a pop-up. Simply change


GuiStreams: Redirecting Streams to Widgets | 627
Free download pdf