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

(yzsuai) #1

class Demo(Frame):
def init(self,parent=None):
Frame.init(self,parent)
self.pack()
Label(self, text ="Basic demos").pack()
Button(self, text='open', command=self.openfile).pack(fill=BOTH)
Button(self, text='save', command=self.savefile).pack(fill=BOTH)
self.open_name = self.save_name = ""
def openfile(self): # save user results
self.open_name = askopenfilename() # use dialog options here
def savefile(self):
self.save_name = asksaveasfilename(initialdir='C:\Python31')


if name == "main":


display window once


print('popup1...')
mydialog = Demo() # attaches Frame to default Tk()
mydialog.mainloop() # display; returns after windows closed
print(mydialog.open_name) # names still on object, though GUI gone
print(mydialog.save_name)


Non GUI section of the program uses mydialog here


display window again


print('popup2...')
mydialog = Demo() # re-create widgets again
mydialog.mainloop() # window pops up again
print(mydialog.open_name) # new values on the object again
print(mydialog.save_name)


Non GUI section of the program uses mydialog again


print('ending...')


This program twice builds and displays a simple two-button main window that
launches file selection dialogs, shown in Figure 10-13. Its output, printed as the GUI
windows are closed, looks like this:


C:\...\PP4E\Gui\Tools> mainloopdemo.py
popup1...
C:/Users/mark/Stuff/Books/4E/PP4E/dev/Examples/PP4E/Gui/Tools/widgets.py
C:/Python31/python.exe
popup2...
C:/Users/mark/Stuff/Books/4E/PP4E/dev/Examples/PP4E/Gui/Tools/guimixin.py
C:/Python31/Lib/tkinter/__init__.py
ending...

Notice how this program calls mainloop twice, to implement two modal user interac-
tions from an otherwise non-GUI script. It’s OK to call mainloop more than once, but
this script takes care to re-create the GUI’s widgets before each call because they are
destroyed when the previous mainloop call exits (widgets are destroyed internally inside
Tk, even though the corresponding Python widget object still exists). Again, this can
make for an odd user experience compared to a traditional GUI program structure—
windows seem to pop up from nowhere—but it’s a quick way to put a GUI face on a
script without reworking its code.


648 | Chapter 10: GUI Coding Techniques

Free download pdf