I l@ve RuBoard Previous Section Next Section

9.4 Creating Dialog Boxes with Tkinter

Credit:Luther Blissett

9.4.1 Problem

You want to create a dialog box (i.e., a new top-level window with buttons to make the window go away).

9.4.2 Solution

For the simplest jobs, you can use the Tkinter Dialog widget:

import Dialog

def ask(title, text, strings=('Yes', 'No'), bitmap='questhead', default=0):
    d = Dialog.Dialog(
        title=title, text=text, bitmap=bitmap, default=default, strings=strings)
    return strings[d.num]

This function shows a modal dialog with the given title and text and as many buttons as there are items in strings. The function doesn't return until the user clicks a button, at which point it returns the string that labels the button.

9.4.3 Discussion

Dialog is simplest when all you want is a dialog box with some text, a title, a bitmap, and all the buttons you want, each with a string label of your choice.

On the other hand, when you're happy with the standard OK and Cancel buttons, you may want to import the tkSimpleDialog module instead. It offers the askinteger, askfloat, and askstring functions, each of which accepts title and prompt arguments, as well as, optionally, initialvalue, minvalue, and maxvalue:

import tkSimpleDialog
x = tkSimpleDialog.askinteger("Choose an integer", "Between 1 and 6 please:",
    initialvalue=1, minvalue=1, maxvalue=6)
print x

Each function pops up a suitable, simple modal dialog and returns either a value entered by the user that meets the constraints you gave, or None if the user clicks Cancel.

9.4.4 See Also

Information about Tkinter can be obtained from a variety of sources, such as Pythonware's An Introduction to Tkinter, by Fredrik Lundh (http://www.pythonware.com/library), New Mexico Tech's Tkinter reference (http://www.nmt.edu/tcc/help/lang/python/docs.html), and various books.

    I l@ve RuBoard Previous Section Next Section