This is a memo of the procedure to use the file dialog with tkinter.
You can use tkinter.filedialog.askdirectory to open a dialog to select a folder. Specify the initial directory with initialdir.
python
import tkinter.filedialog
iDir = os.path.abspath(os.path.dirname(__file__))
folder_name = tkinter.filedialog.askdirectory(initialdir=iDir)
You can open a file dialog with tkinter.filedialog.askopenfilename. Specify the candidate file pattern with filetypes, and specify the first directory to open with initialdir. If you want to select multiple files, use tkinter.filedialog.askopenfilenames.
python
import tkinter.filedialog
fTyp = [("", "*")]
iDir = os.path.abspath(os.path.dirname(__file__))
file_name = tkinter.filedialog.askopenfilename(filetypes=fTyp, initialdir=iDir)
You can specify the file extension. Give in the order of heading and pattern.
python
fTyp = [("data file", "*.csv;*.xlsx;*.xls")]
You can also select by partial match of the file name.
python
fTyp = [("log file", "log*")]
When actually using it, I think it's best to use it like this.
python
import os
import tkinter as tk
import tkinter.filedialog
class TkinterClass:
def __init__(self):
root = tk.Tk()
root.geometry("500x350")
button = tk.Button(root, text='Open file dialog', font=('', 20),
width=24, height=1, bg='#999999', activebackground="#aaaaaa")
button.bind('<ButtonPress>', self.file_dialog)
button.pack(pady=40)
self.file_name = tk.StringVar()
self.file_name.set('Not selected')
label = tk.Label(textvariable=self.file_name, font=('', 12))
label.pack(pady=0)
button = tk.Button(root, text='Open folder dialog', font=('', 20),
width=24, height=1, bg='#999999', activebackground="#aaaaaa")
button.bind('<ButtonPress>', self.folder_dialog)
button.pack(pady=40)
self.folder_name = tk.StringVar()
self.folder_name.set('Not selected')
label = tk.Label(textvariable=self.folder_name, font=('', 12))
label.pack(pady=10)
root.mainloop()
def file_dialog(self, event):
fTyp = [("", "*")]
iDir = os.path.abspath(os.path.dirname(__file__))
file_name = tk.filedialog.askopenfilename(filetypes=fTyp, initialdir=iDir)
if len(file_name) == 0:
self.file_name.set('Canceled selection')
else:
self.file_name.set(file_name)
def folder_dialog(self, event):
iDir = os.path.abspath(os.path.dirname(__file__))
folder_name = tk.filedialog.askdirectory(initialdir=iDir)
if len(folder_name) == 0:
self.folder_name.set('Canceled selection')
else:
self.folder_name.set(folder_name)
if __name__ == '__main__':
TkinterClass()
Let's try
Works well import
import tkinter as tk
import tkinter.filedialog
tk.filedialog.askdirectory(initialdir=iDir)
Import that doesn't work
import tkinter as tk
tk.filedialog.askdirectory(initialdir=iDir)
why! ??
Recommended Posts