If you press OK here, Quitter runs the Frame quit method to end the GUI to which this
button is attached (really, the mainloop call). But to really understand how such a spring-
loaded button can be useful, we need to move on and study a client GUI in the next
section.
A dialog demo launcher bar
So far, we’ve seen a handful of standard dialogs, but there are quite a few more. Instead
of just throwing these up in dull screenshots, though, let’s write a Python demo script
to generate them on demand. Here’s one way to do it. First of all, in Example 8-8 we
write a module to define a table that maps a demo name to a standard dialog call (and
we use lambda to wrap the call if we need to pass extra arguments to the dialog
function).
Example 8-8. PP4E\Gui\Tour\dialogTable.py
define a name:callback demos table
from tkinter.filedialog import askopenfilename # get standard dialogs
from tkinter.colorchooser import askcolor # they live in Lib\tkinter
from tkinter.messagebox import askquestion, showerror
from tkinter.simpledialog import askfloat
demos = {
'Open': askopenfilename,
'Color': askcolor,
'Query': lambda: askquestion('Warning', 'You typed "rm *"\nConfirm?'),
'Error': lambda: showerror('Error!', "He's dead, Jim"),
'Input': lambda: askfloat('Entry', 'Enter credit card number')
}
I put this table in a module so that it might be reused as the basis of other demo scripts
later (dialogs are more fun than printing to stdout). Next, we’ll write a Python script,
shown in Example 8-9, which simply generates buttons for all of this table’s entries—
use its keys as button labels and its values as button callback handlers.
Example 8-9. PP4E\Gui\Tour\demoDlg.py
"create a bar of simple buttons that launch dialog demos"
from tkinter import * # get base widget set
from dialogTable import demos # button callback handlers
from quitter import Quitter # attach a quit object to me
class Demo(Frame):
def init(self, parent=None, options):
Frame.init(self, parent, options)
self.pack()
Label(self, text="Basic demos").pack()
for (key, value) in demos.items():
Button(self, text=key, command=value).pack(side=TOP, fill=BOTH)
Quitter(self).pack(side=TOP, fill=BOTH)
430 | Chapter 8: A tkinter Tour, Part 1