[Rod Stephens Books]
Index Books Python Examples About Rod Contact
[Mastodon] [Bluesky]
[Build Your Own Ray Tracer With Python]

[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

Title: Use file open and save dialogs in Python and tkinter

[This example shows how to use file open and save dialogs in Python and tkinter.]


This program uses tkinter dialogs to let the user select a file for opening and another file for saving. It begins with some import statements including the following.

import tkinter.messagebox as msg from tkinter.filedialog import askopenfilename, asksaveasfilename

When you select the File menu's Open command or press Ctrl+O, the program executes the following code.

def mnu_open(self): '''Open a file.''' filetypes = [ ('Text files', '*.txt'), ('Python Files', '*.py *.ipynb'), ('All Files', '*,*')] filename = askopenfilename(filetypes=filetypes) if len(filename) > 0: msg.showinfo('Open File', filename)

This code creates a list that defines the file filters that the dialog should use. Each entry in the list is a two-string tuple. The first string gives the text that should be displayed for the filter such as Python Files. The second string lists file patterns separated by spaces as in *.py *.ipynb.

Next the code calls the askopenfilename method passing it the filter list. That method displays the file selection dialog and returns a string giving the full path to the selected file.

If the user cancels the dialog, the method returns an empty string.

Note that askopenfilename returns the name of the file. Alternatively you can use the askopenfile method, which opens the selected file in read mode.

You can also use the askopenfilenames and askopenfiles methods to let the user select multiple files.

When you select the File menu's Save As command or press Ctrl+S, the program executes the following code.

def mnu_save_as(self): '''Save a file.''' filetypes = [ ('Text files', '*.txt'), ('Python Files', '*.py *.ipynb'), ('All Files', '*,*')] filename = asksaveasfilename(filetypes=filetypes) if len(filename) > 0: msg.showinfo('Save File', filename)

This code creates a filter list as before. It then calls asksaveasfilename to let the user select a file. This method returns the file's full path or an empty string if the user cancels the dialog.

Download the example to see all of the details.

© 2024 - 2025 Rocky Mountain Computer Consulting, Inc. All rights reserved.