python logo

Tkinter tkFileDialog module

Python hosting: Host, run, and code Python in the cloud!

tkFileDialog is a module with open and save dialog functions.
Instead of implementing those in Tkinter GUI on your own.

Related courses

Overview
An overview of file dialogs:

Tkinter Open File

The askopenfilename function to creates an file dialog object. The extensions are shown in the bottom of the form (Files of type). The code below will simply show the dialog and return the filename. If a user presses cancel the filename is empty. On a Windows machine change the initialdir to “C:\”.

Python 2.7 version:

Function Parameters Purpose
.askopenfilenameDirectory, Title, Extension To open file: Dialog that requests selection of an existing file.
.asksaveasfilenameDirectory, Title, Extension) To save file: Dialog that requests creation or replacement of a file.
.askdirectoryNoneTo open directory
from Tkinter import *from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog

root = Tk()
root.filename = tkFileDialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
print (root.filename)

Python 3 version:


from tkinter import filedialog
from tkinter import *

root = Tk()
root.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
print (root.filename)

Here is an example (on Linux):

tkfiledialog Tkinter askopenfilename tkfiledialog Tkinter askopenfilename

Tkinter Save File


The asksaveasfilename function prompts the user with a save file dialog.

Python 2.7 version


from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog

root = Tk()
root.filename = tkFileDialog.asksaveasfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
print (root.filename)

Python 3 version


from tkinter import filedialog
from tkinter import *

root = Tk()
root.filename = filedialog.asksaveasfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
print (root.filename)

Tkinter Open Directory


The askdirectory presents the user with a popup for directory selection.

Python 2.7 version


from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog
root = Tk()
root.directory = tkFileDialog.askdirectory()
print (root.directory)

tkinter-askdirectory tkinter askdirectory

If you are new to programming Tkinter, I highly recommend this course.

download tkinter examples

BackNext





Leave a Reply: