Filedialog in tkinter
Tkinter File Dialogs.
Tkinter have a class filedialog which is used when we have to work with files and directory.
basically filedialog class have a bunch of functions/methods which basically makes a dialog in which the user can selects a single or multiple file at a time ( depends on configuration or method which we use ) and it returns the path of that specific file or directory.
The theme of filedialog is directly depend on the operating system themes.
Types of filedialog available with Tkinter.
- filedialog.asksaveasfilename()
- filedialog.asksaveasfile()
- filedialog.askopenfilename()
- filedialog.askopenfile()
- filedialog.askdirectory()
- filedialog.askopenfilenames()
- filedialog.askopenfiles()
As you can see the Tkinter only have Two types of Filedialog.
1 is for open files and directory
2 is for save files.
and these two types are further divide into 7 categories.
File dialog Options.
Options | Type | Description | |
defaultextension | string | An extension to add to the filename, if not explicitly given by the user. The string should include the leading dot (ignored by the open dialog). | |
filetypes | list | Sequence of (label, pattern) tuples. The same label may occur with several patterns. Use “*” as the pattern to indicate all files. | |
initialdir | string | Initial Directory | |
initialfile | string | Initial file | |
parent | widget | Which window to place the message box on top of. When the dialog is closed, the focus is returned to the parent window. | |
title | string | Message box title. |
So lets code it.
# Tkinter - Dynamic Coding
# filedialog... ...
# Import Library
from tkinter import *
from tkinter import filedialog
root =Tk()
root.title("Dynamic Coding")
root.geometry('300x200')
val = filedialog.askdirectory(title='Select a Directory')
print(val)
# returns the path of selected Folder or if we select
# cancel button it returns Nothing just blank spaces
root.mainloop()
Output.
In our example code we use askdirectory method.
Difference between askopenfilename and askopenfilenames methods.
# Tkinter - Dynamic Coding
# filedialog... ...
# Import Library
from tkinter import *
from tkinter import filedialog
root =Tk()
root.title("Dynamic Coding")
root.geometry('300x200')
val1 = filedialog.askopenfilename()
# user can choose only a single file at a time.
val2 = filedialog.askopenfilenames()
# user can choose multiple files at a single time.
print(val1)
print(val2)
root.mainloop()
Recommended Posts:
Thank you ..
If have Any doubts and Errors , comment section is open for you and we will try to solve your doubts as soon as possible.
No comments