Before we look at what to put in that application work area, let’s take a look at another important part of GUI programming: displaying dialogs and message boxes.
Starting with Tk 4.2, the Tk library provides a set of standard dialogs that can be used to display message boxes, and to select files and colors. In addition, Tkinter provides some simple dialogs allowing you to ask the user for integers, floating point values, and strings. Where possible, these standard dialogs use platform-specific mechanisms, to get the right look and feel.
The tkMessageBox module provides an interface to the message dialogs.
The easiest way to use this module is to use one of the convenience functions: showinfo, showwarning, showerror, askquestion, askokcancel, askyesno, or askretrycancel. They all have the same syntax:
tkMessageBox.function(title, message [, options]).
The title argument is shown in the window title, and the message in the dialog body. You can use newline characters (“\n”) in the message to make it occupy multiple lines. The options can be used to modify the look; they are explained later in this section.
The first group of standard dialogs is used to present information. You provide the title and the message, the function displays these using an appropriate icon, and returns when the user has pressed OK. The return value should be ignored.
Here’s an example:
try: fp = open(filename) except: tkMessageBox.showwarning( "Open file", "Cannot open this file\n(%s)" % filename ) return
The second group is used to ask questions. The askquestion function returns the strings “yes” or “no” (you can use options to modify the number and type of buttons shown), while the others return a true value of the user gave a positive answer (ok, yes, and retry, respectively).
if tkMessageBox.askyesno("Print", "Print this report?"): report.print()
[Screenshots made on a Swedish version of Windows 95. Hope you don’t mind…]
Message Box Options
If the standard message boxes are not appropriate, you can pick the closest alternative (askquestion, in most cases), and use options to change it to exactly suit your needs. You can use the following options (note that message and title are usually given as arguments, not as options).
Which button to make default: ABORT, RETRY, IGNORE, OK, CANCEL, YES, or NO (the constants are defined in the tkMessageBox module).
Which icon to display: ERROR, INFO, QUESTION, or WARNING
The message to display (the second argument to the convenience functions). May contain newlines.
Which window to place the message box on top of. When the message box is closed, the focus is returned to the parent window.
Message box title (the first argument to the convenience functions).
Message box type; that is, which buttons to display: ABORTRETRYIGNORE, OK, OKCANCEL, RETRYCANCEL, YESNO, or YESNOCANCEL.