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

(yzsuai) #1

from tkinter import *
from multiprocessing import Process
demoModules = ['demoDlg', 'demoRadio', 'demoCheck', 'demoScale']


def runDemo(modname): # run in a new process
module = import(modname) # build gui from scratch
module.Demo().mainloop()


if name == 'main':
for modname in demoModules: # in main only!
Process(target=runDemo, args=(modname,)).start()


root = Tk() # parent process GUI
root.title('Processes')
Label(root, text='Multiple program demo: multiprocessing', bg='white').pack()
root.mainloop()


Operationally, this version differs on Windows only in that:



  • The child processes’ standard output shows up in the window where the script was
    launched, including the outputs of both dialog demos themselves and all demo
    windows’ State buttons.

  • The script doesn’t truly exit if any children are still running: the shell where it is
    launched is blocked if the main process’s window is closed while children are still
    running, unless we set the child processes’ daemon flag to True before they start as
    we saw in Chapter 5—in which case all child programs are automatically shut down
    when their parent is (but parents may still outlive their children).


Also observe how we start a simple named function in the new Process. As we learned
in Chapter 5, the target must be pickleable on Windows (which essentially means im-
portable), so we cannot use lambdas to pass extra data in the way we typically could
in tkinter callbacks. The following coding alternatives both fail with errors on
Windows:


Process(target=(lambda: runDemo(modname))).start() # these both fail!

Process(target=(lambda: __import__(modname).Demo().mainloop())).start()

We won’t recode our GUI program launcher script with any of the other techniques
available, but feel free to experiment on your own using Chapter 5 as a resource. Al-
though not universally applicable, the whole point of tools like the PortableLauncher
class is to hide such details so we can largely forget them.


Cross-program communication


Spawning GUIs as programs is the ultimate in code independence, but it makes the
lines of communication between components more complex. For instance, because the
demos run as programs here, there is no easy way to run all their report methods from
the launching script’s window pictured in the upper right of Figure 8-35. In fact, the


480 | Chapter 8: A tkinter Tour, Part 1

Free download pdf