Over a million developers have joined DZone.

Simple Dialogs W Python

Code for creating simple dir and file selectors using functions
that are built in to python. The python 2.5 docs are missing info
on simple dialogs in python. These dialogs are complete Tkinter
widgets designed to get simple information.

You can learn more about these dialogs by inspecting the
file in /python/Lib/lib-tk  (in python 2.5)

Some of this code is a copy of the code from:


with the suggestions in the comments added. The reason I copied it here
is to keep all the snippets I use in one place.

All credit goes to the original author: Sébastien Sauvage

# ======== Select a directory:

import Tkinter, tkFileDialog, tkMessageBox, tkSimpleDialog

root = Tkinter.Tk()
dirname = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Please select a directory')
if len(dirname ) > 0:
    print "You chose %s" % dirname 

# ======== Select a file for opening:
import Tkinter,tkFileDialog

root = Tkinter.Tk()
file = tkFileDialog.askopenfile(parent=root,mode='rb',title='Choose a file')
if file != None:
    data = file.read()
    print "I got %d bytes from this file." % len(data)

# ======== "Save as" dialog:
import Tkinter,tkFileDialog

myFormats = [
    ('Windows Bitmap','*.bmp'),
    ('Portable Network Graphics','*.png'),
    ('JPEG / JFIF','*.jpg'),
    ('CompuServer GIF','*.gif'),

root = Tkinter.Tk()
fileName = tkFileDialog.asksaveasfilename(parent=root,filetypes=myFormats ,title="Save the image as...")
if len(fileName ) > 0:
    print "Now saving under %s" % nomFichier

# ======== Message boxes
root = Tkinter.Tk()
x=tkMessageBox.askquestion(title='Test',message='A user prompt') # has yes and no buttons returns strings "yes" or "no"
x=tkMessageBox.askyesno(title='Test',message='A user prompt')    # has yes and no buttons returns True False
x=tkMessageBox.askokcancel(title='Test',message='A user prompt') # returns True False
x=tkMessageBox.askretrycancel(title='Test',message='A user prompt')  # returns True False

# ======== Data Entry Dialogs
root = Tkinter.Tk()
x=tkSimpleDialog.askstring('Test', 'Enter string: ')  # has OK and Cancel buttons - returns None on Cancel
x=tkSimpleDialog.askinteger('Test', 'Enter an integer: ')
x=tkSimpleDialog.askfloat('Test', 'Enter an float: ')


Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}