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

(yzsuai) #1

Independent Windows


Once you have a set of component classes coded as frames, any parent will work—
both other frames and brand-new, top-level windows. Example 8-33 attaches instances
of all four demo bar objects to their own independent Toplevel windows, instead of
the same container.


Example 8-33. PP4E\Gui\Tour\demoAll-win.py


"""
4 demo classes in independent top-level windows;
not processes: when one is quit all others go away, because all windows run in
the same process here; make Tk() first here, else we get blank default window
"""


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


def makePopups(modnames):
demoObjects = []
for modname in modnames:
module = import(modname) # import by name string
window = Toplevel() # make a new window
demo = module.Demo(window) # parent is the new window
window.title(module.name)
demoObjects.append(demo)
return demoObjects


def allstates(demoObjects):
for obj in demoObjects:
if hasattr(obj, 'report'):
print(obj.module, end=' ')
obj.report()


root = Tk() # make explicit root first
root.title('Popups')
demos = makePopups(demoModules)
Label(root, text='Multiple Toplevel window demo', bg='white').pack()
Button(root, text='States', command=lambda: allstates(demos)).pack(fill=X)
root.mainloop()


We met the Toplevel class earlier; every instance generates a new window on your
screen. The net result is captured in Figure 8-34. Each demo runs in an independent
window of its own instead of being packed together in a single display.


476 | Chapter 8: A tkinter Tour, Part 1

Free download pdf