Skip to Content
Python Cookbook
book

Python Cookbook

by Alex Martelli, David Ascher
July 2002
Intermediate to advanced
608 pages
15h 46m
English
O'Reilly Media, Inc.
Content preview from Python Cookbook

Creating Dialog Boxes with Tkinter

Credit:Luther Blissett

Problem

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

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.

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.

See Also

Information about Tkinter ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Python Cookbook - Second Edition

Modern Python Cookbook - Second Edition

Steven F. Lott
Python Cookbook, 3rd Edition

Python Cookbook, 3rd Edition

David Beazley, Brian K. Jones

Publisher Resources

ISBN: 0596001673Supplemental ContentCatalog PageErrata