Python save file dialog

Create a Save File Dialog in Tkinter

Tkinter is a popular Python library for building graphical user interfaces (GUIs). It provides a variety of widgets and functions that can be used to create and display dialog boxes, such as message boxes, file dialogs, and color dialogs. In this tutorial, we will learn how to create a save file dialog in Tkinter, which allows the user to select a location anywhere on their device to save a file.

Save File Dialogs in Tkinter

Let’s create our first save file dialog with Tkinter!

First we need to make additional import from the Tkinter module (if you haven’t done import * from tkinter ). You can think of “filedialog” as a submodule inside Tkinter which allows us to create various types of dialogs.

import tkinter as tk from tkinter import filedialog

Now all we have to do is use the asksaveasfile() method, and pass in the required parameters.

There are no “compulsory” parameters (we can just leave everything to the default settings). But we went ahead anyway of defined title and default extension parameters anyway. Here is the full code.

import tkinter as tk from tkinter import filedialog root = tk.Tk() def save_file(): file = filedialog.asksaveasfile(title = "Save File", defaultextension=".txt") if file: file.write("This is the content of the file.") file.close() save_button = tk.Button(root, text="Save File", command=save_file) save_button.pack() root.mainloop()

The default extension is the automatic extension applied to the save file if you did not pick one. The title parameter controls the text that appears on the top-left corner of the dialog.

Читайте также:  What php version is my server running

Save File Dialog

Let’s take a look at some other possible customizations.

One thing we can do is control where the Save File Dialog shows up (initially). By passing in a directory path in the initialdir parameter, this becomes possible.

The below code demonstrates this (Save Dialog will show up in C-drive).

import tkinter as tk from tkinter import filedialog root = tk.Tk() def save_file(): file = filedialog.asksaveasfile(title = "Save File", initialdir = "C:/", defaultextension=".txt") if file: file.write("This is the content of the file.") file.close() save_button = tk.Button(root, text="Save File", command=save_file) save_button.pack() root.mainloop()

Another important feature is the “filetypes” parameter. We can define various “file types” (e.g text or Excel), which the user can select from when saving his file (the filetype selected will become the extension of the saved file)

Pay attention to how the filetypes are defined. We have an array of tuples. Each tuple has two values, the first being the label, and the second being the actual extension.

import tkinter as tk from tkinter import filedialog root = tk.Tk() def save_file(): types = [("Text files", "*.txt"), ("Excel files", "*.xlsx"), ("All files", "*.*")] file = filedialog.asksaveasfile(title = "Save File", initialdir = ".", defaultextension=".txt", filetypes=types) if file: file.write("This is the content of the file.") file.close() save_button = tk.Button(root, text="Save File", command=save_file) save_button.pack() root.mainloop()

Maybe you did not notice, but we changed the initialdir in the above example to a “.” (dot). This means that the Save Dialog will show up in the same folder as your Python script.

This marks the end of the Tkinter Save File Dialog Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions about the tutorial content can be asked in the comments section below.

Источник

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.

Источник

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