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

(yzsuai) #1

Note that this is different from using nested (recursive) mainloop calls to implement
modal dialogs, as we did in Chapter 8. In that mode, the nested mainloop call returns
when the dialog’s quit method is called, but we return to the enclosing mainloop layer
and remain in the realm of event-driven programming. Example 10-22 instead runs
mainloop two different times, stepping into and out of the event-driven model twice.


Finally, note that this scheme works only if you don’t have to run any non-GUI code
while the GUI is open, because your script’s mainline code is inactive and blocked while
mainloop runs. You cannot, for example, apply this technique to use utilities like those
in the guiStreams module we met earlier in this chapter to route user interaction from
non-GUI code to GUI windows. The GuiInput and GuiOutput classes in that example
assume that there is a mainloop call running somewhere (they’re GUI-based, after all).
But once you call mainloop to pop up these windows, you can’t return to your non-GUI
code to interact with the user or the GUI until the GUI is closed and the mainloop call
returns. The net effect is that these classes can be used only in the context of a fully
GUI program.


But really, this is an artificial way to use tkinter. Example 10-22 works only because
the GUI can interact with the user independently, while the mainloop call runs; the
script is able to surrender control to the tkinter mainloop call and wait for results. That
scheme won’t work if you must run any non-GUI code while the GUI is open. Because
of such constraints, you will generally need a main-window-plus-callbacks model in
most GUI programs—callback code runs in response to user interaction while the GUI
remains open. That way, your code can run while GUI windows are active. For an
example, see earlier in this chapter for the way the non-GUI packer and unpacker scripts
were run from a GUI so that their results appear in a GUI; technically, these scripts are
run in a GUI callback handler so that their output can be routed to a widget.


Adding a GUI As a Separate Program: Sockets (A Second Look)


As mentioned earlier, it’s also possible to spawn the GUI part of your application as a
completely separate program. This is a more advanced technique, but it can make
integration simple for some applications because of the loose coupling it implies. It can,
for instance, help with the guiStreams issues of the prior section, as long as inputs and
outputs are communicated to the GUI over Inter-Process Communication (IPC)


Figure 10-13. GUI window popped up by non-GUI main program


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