Many Python applications need to ask the user if they want to a open a file or folder or save a file. The tkinter library has built in dialog functions for this exact purpose. Here is an example of how to use the askopenfilename, asksaveasfile, and askdirectory functions with some common configurations.
from tkinter import *
from pathlib import Path
from tkinter.filedialog import askopenfilename, asksaveasfile, askdirectory
class Window(Frame):
def __init__(self, master=None, cnf={}, **kw):
super().__init__(master, cnf, **kw)
self.open = Button(self, text='Open', command=self.open_file)
self.save = Button(self, text='Save', command=self.save_file)
self.ask_dir = Button(self, text='Folder', command=self.ask_folder)
self.exit = Button(self, text='Exit', command=self.quit)
for b in (self.open, self.save, self.ask_dir, self.exit):
b.pack(side=LEFT, fill=BOTH)
self.pack()
def open_file(self):
file = askopenfilename(filetypes=(("Python files", "*.py"),
("All files", "*.*")),
title='Open File',
initialdir=str(Path.home()))
if file:
print(file)
else:
print('Cancelled')
def save_file(self):
file = asksaveasfile(filetypes=(("Python files", "*.py"),
("All files", "*.*")),
title='Save File',
initialdir=str(Path.home()))
if file:
print(file)
else:
print('Cancelled')
def ask_folder(self):
folder = askdirectory(title='Pick a folder', initialdir=str(Path.home()))
if folder:
print(folder)
else:
print('Cancelled')
if __name__ == '__main__':
win = Window(Tk())
win.mainloop()
askopenfilename
You use askopenfilename when you want to open a file. It will return the absolute path of the file as a string if the user picks a file, or it will return None if the user cancels. You can restict the file types by passing an Iterable of tuples to the filetypes argument. If you do not specify an initialdir argument, it will default to the root of the user’s disk. I usually prefer to set it to the user’s home directory using Path.home() but you can adjust this to your application’s needs. The dialog will look specific to the user’s platform.
def open_file(self):
file = askopenfilename(filetypes=(("Python files", "*.py"),
("All files", "*.*")),
title='Open File',
initialdir=str(Path.home())
if file:
print(file)
else:
print('Cancelled')
asksaveasfile
You can use this dialog when you want to perform a save operation. It takes arguments that are similar to askopenfilename, but it will return a file handler object opened in write mode (if you use the default arguments) rather than a string. You can then proceed with your save code. This function also returns None if the user cancels.
def save_file(self):
file = asksaveasfile(filetypes=(("Python files", "*.py"),
("All files", "*.*")),
title='Save File',
initialdir=str(Path.home()))
if file:
print(file)
else:
print('Cancelled')
askdirectory
This function is used to let the user pick a folder. It will return a string if the user picked a folder or None if they chose to cancel.
def ask_folder(self):
folder = askdirectory(title='Pick a folder', initialdir=str(Path.home()))
if folder:
print(folder)
else:
print('Cancelled')
Like this:
Like Loading...