Python select file dialog

Python Tkinter filedialog

The Python Tkinter filedialog module offers you a set of unique dialogs to be used when dealing with files. Tkinter has a wide variety of different dialogs, but the ones in filedialog are specifically designed for file selection. And as expected of dialog boxes, these are done in a very user friendly manner.

Below is a list of all the different Dialog options available. Make sure to import filedialog from tkinter as we have shown below. If you want to use tkinter as well as filedialog (which you most definitely will) you will have to import tkinter separately.

from tkinter import filedialog filedialog.asksaveasfilename() filedialog.asksaveasfile() filedialog.askopenfilename() filedialog.askopenfile() filedialog.askdirectory() filedialog.askopenfilenames() filedialog.askopenfiles()

FileDialog Options

  • parent – The Window on to which the dialog is to be placed
  • title – The name that appears on the dialog
  • initialdir – The directory the dialog first opens up in.
  • initialfile – The file that the dialog has selected when it is opened.
  • filetypes – Determines that type of the files to be loaded/saved in the dialogs. Passed as a tuple in a (Label, Filetype) format. You may also use the * wild card which applies to all filetypes. You can pass multiple tuples as well for multiple options.
  • defaultextension – Default extension to be applied to files when appending to them. (Only applies to save dialogs)
  • multiple – When true, it allows the selection of multiple items.
Читайте также:  Import CSV File into MySQL using PHP

Alot of these options are actually optional. At most you’ll find yourself using 3 – 4 per function.

Returning a File Path

CodersLegacy Tkinter FileDialog

Pay attention to the File types option mentioned here. Notice how the option for filetypes above has effected the options in the GUI.

import tkinter as tk from tkinter import filedialog path = filedialog.askopenfilename(initialdir="/", title="Select file", filetypes=(("txt files", "*.txt"),("all files", "*.*")))

Once you select a file, it’s file path will be returned back into your python program for you to use. Remember, you can only select files with this, not folders.

Use the askopenfilenames function if you want to select multiple files.

Selecting a File

The difference between the askopenfile function and askopenfilename(s) is that one returns the actual File object, and one simply returns the file path. In the example below, this is apparent. Where we select a random text file and see it’s output on screen after calling the read function.

import tkinter as tk from tkinter import filedialog root = tk.Tk() path = filedialog.askopenfile(initialdir="/", title="Select file", filetypes=(("txt files", "*.txt"),("all files", "*.*"))) print(path.read()) root.mainloop()

Below is the text that was written in the file we selected.

This is Python Tkinter FileDialog. Amazing right?

The look of the GUI is the exact same as the one for the askopenfilename function. And just like it, askopenfiles can be used to open several files.

Saving a File

The asksaveasfile function is used to save a file in a specified location. You get to select this location through the same selection GUI shown in the examples above.

import tkinter as tk from tkinter import filedialog root = tk.Tk() path = filedialog.asksaveasfile(initialdir="/", title="Save file", filetypes=(("txt files", "*.txt"),("all files", "*.*"))) root.mainloop()

For instance, you may navigate to the Desktop and save a file there with the name of your choice. Be sure to mention the extension when saving the files, otherwise use the defaultextension option to assign an extension to your files.

CodersLegacy Tkinter FileDialog

The above image shows the GUI for the asksaveasfile function. The biggest difference is the Save button instead of the Open button.

Selecting a Directory

This function is just like the askopenfilename function, except that it’s not used to select files, rather it selects directories (folders) and return their file path.

import tkinter as tk from tkinter import filedialog root = tk.Tk() path = filedialog.askdirectory(initialdir="/", title="Select file") print(path) root.mainloop()

We selected the Users folder in C drive, and the following file path was returned.

Be sure not to include the filetypes option here. Folders don’t have filetypes after all.

This marks the end of the Python Tkinter filedialog article. Suggestions and Contributions for CodersLegacy are more than welcome. Any questions regarding the above material can be asked in the comments section below.

Head back to the main Tkinter article to learn about other great widgets!

Источник

Tkinter Dialogs¶

tkinter.simpledialog — Standard Tkinter input dialogs¶

The tkinter.simpledialog module contains convenience classes and functions for creating simple modal dialogs to get a value from the user.

tkinter.simpledialog. askfloat ( title , prompt , ** kw ) ¶ tkinter.simpledialog. askinteger ( title , prompt , ** kw ) ¶ tkinter.simpledialog. askstring ( title , prompt , ** kw ) ¶

The above three functions provide dialogs that prompt the user to enter a value of the desired type.

class tkinter.simpledialog. Dialog ( parent , title = None ) ¶

The base class for custom dialogs.

body ( master ) ¶

Override to construct the dialog’s interface and return the widget that should have initial focus.

buttonbox ( ) ¶

Default behaviour adds OK and Cancel buttons. Override for custom button layouts.

tkinter.filedialog — File selection dialogs¶

The tkinter.filedialog module provides classes and factory functions for creating file/directory selection windows.

Native Load/Save Dialogs¶

The following classes and functions provide file dialog windows that combine a native look-and-feel with configuration options to customize behaviour. The following keyword arguments are applicable to the classes and functions listed below:

Static factory functions

The below functions when called create a modal, native look-and-feel dialog, wait for the user’s selection, then return the selected value(s) or None to the caller.

tkinter.filedialog. askopenfile ( mode = ‘r’ , ** options ) ¶ tkinter.filedialog. askopenfiles ( mode = ‘r’ , ** options ) ¶

The above two functions create an Open dialog and return the opened file object(s) in read-only mode.

tkinter.filedialog. asksaveasfile ( mode = ‘w’ , ** options ) ¶

Create a SaveAs dialog and return a file object opened in write-only mode.

tkinter.filedialog. askopenfilename ( ** options ) ¶ tkinter.filedialog. askopenfilenames ( ** options ) ¶

The above two functions create an Open dialog and return the selected filename(s) that correspond to existing file(s).

tkinter.filedialog. asksaveasfilename ( ** options ) ¶

Create a SaveAs dialog and return the selected filename.

tkinter.filedialog. askdirectory ( ** options ) ¶

class tkinter.filedialog. Open ( master = None , ** options ) ¶ class tkinter.filedialog. SaveAs ( master = None , ** options ) ¶

The above two classes provide native dialog windows for saving and loading files.

Convenience classes

The below classes are used for creating file/directory windows from scratch. These do not emulate the native look-and-feel of the platform.

class tkinter.filedialog. Directory ( master = None , ** options ) ¶

Create a dialog prompting the user to select a directory.

The FileDialog class should be subclassed for custom event handling and behaviour.

Create a basic file selection dialog.

cancel_command ( event = None ) ¶

Trigger the termination of the dialog window.

Event handler for double-click event on directory.

Event handler for click event on directory.

Event handler for double-click event on file.

Event handler for single-click event on file.

filter_command ( event = None ) ¶

Filter the files by directory.

Retrieve the file filter currently in use.

Retrieve the currently selected item.

go ( dir_or_file = os.curdir , pattern = ‘*’ , default = » , key = None ) ¶

Render dialog and start event loop.

Exit dialog returning current selection.

Exit dialog returning filename, if any.

Update the current file selection to file.

class tkinter.filedialog. LoadFileDialog ( master , title = None ) ¶

A subclass of FileDialog that creates a dialog window for selecting an existing file.

Test that a file is provided and that the selection indicates an already existing file.

class tkinter.filedialog. SaveFileDialog ( master , title = None ) ¶

A subclass of FileDialog that creates a dialog window for selecting a destination file.

Test whether or not the selection points to a valid file that is not a directory. Confirmation is required if an already existing file is selected.

tkinter.commondialog — Dialog window templates¶

The tkinter.commondialog module provides the Dialog class that is the base class for dialogs defined in other supporting modules.

class tkinter.commondialog. Dialog ( master = None , ** options ) ¶ show ( color = None , ** options ) ¶

Источник

tkinter filedialog

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

This page is a collection of python tkinter file dialogs. The code is displayed here along with screenshots. Dialogs included in tkinter let you ask for a filename or directory.

tkinter file dialogs are easy to use, but not that easy to find out how to use. The main problem is that there is no simple example of how to do it. This article tries to fill the gap.

Related course:

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).

tkinter.tk.askopenfilename is an extension of the askopenfilename function provided in Tcl/Tk.

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:

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

Consider a scenario where your program needs to get a directory, the user clicked on the ok button and now you want to determine the path.

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

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

Источник

Оцените статью