Quick and easy file dialog in Python?
Tkinter is the easiest way if you don't want to have any other dependencies.
To show only the dialog without any other GUI elements, you have to hide the root window using the withdraw
method:
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
Python 2 variant:
import Tkinter, tkFileDialog
root = Tkinter.Tk()
root.withdraw()
file_path = tkFileDialog.askopenfilename()
Choosing a file in Python with simple Dialog
How about using tkinter?
from Tkinter import Tk # from tkinter import Tk for Python 3.x
from tkinter.filedialog import askopenfilename
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
print(filename)
Done!
How to open and select a file in Python
As mentioned in the comments, you should provide a minimal reproducible example. Since you are a new member, I am giving you this example, which can be found here. https://www.geeksforgeeks.org/loading-images-in-tkinter-using-pil/
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
def open_img():
# Select the Imagename from a folder
x = openfilename()
# opens the image
img = Image.open(x)
# resize the image and apply a high-quality down sampling filter
img = img.resize((250, 250), Image.ANTIALIAS)
# PhotoImage class is used to add image to widgets, icons etc
img = ImageTk.PhotoImage(img)
# create a label
panel = Label(root, image=img)
# set the image as img
panel.image = img
panel.grid(row=2)
def openfilename():
# open file dialog box to select image
# The dialogue box has a title "Open"
filename = filedialog.askopenfilename(title='"pen')
return filename
# Create a window
root = Tk()
# Set Title as Image Loader
root.title("Image Loader")
# Set the resolution of window
root.geometry("550x300+300+150")
# Allow Window to be resizable
root.resizable(width=True, height=True)
# Create a button and place it into the window using grid layout
btn = Button(root, text='open image', command=open_img).grid(row=1, columnspan=4)
root.mainloop()
Python, Dash: Tkinter openfile dialog works fine only the first time but fails afterwards
In callback
you
- create tkinter main window
root = tkinter.Tk()
- hide it
root.withdraw()
but you never destroy it when you exit file dialog.
When it runs again callback
then it tries to create second main window and it makes conflict with previous (hidden) main window.
If I use root.destroy()
then code works correctly.
app.callback(
Output(component_id='selected_directory', component_property='children'),
Input(component_id='open_excel_button', component_property='n_clicks'),
prevent_initial_call=True
)
def open_excel_function(open_excel):
print ('*** 1A. Callback open_file_dialog')
ctx = dash.callback_context
trigger = ctx.triggered[0]['prop_id'].split('.')[0]
print("***", trigger, "is triggered.")
root = tkinter.Tk()
root.withdraw()
# root.iconbitmap(default='Extras/transparent.ico')
if trigger == 'open_excel_button':
file_directory = tkinter.filedialog.askopenfilename(initialdir=FILE_DIR)
print('***', file_directory)
else:
file_directory = None
root.destroy() # <--- SOLUTION
return file_directory
or even
def open_excel_function(open_excel):
print ('*** 1A. Callback open_file_dialog')
ctx = dash.callback_context
trigger = ctx.triggered[0]['prop_id'].split('.')[0]
print("***", trigger, "is triggered.")
if trigger == 'open_excel_button':
root = tkinter.Tk()
root.withdraw()
# root.iconbitmap(default='Extras/transparent.ico')
file_directory = tkinter.filedialog.askopenfilename(initialdir=FILE_DIR)
print('***', file_directory)
root.destroy() # <--- SOLUTION
else:
file_directory = None
return file_directory
EDIT:
If you want to get only dirname then maybe you should use tkinter.filedialog.askdirectory()
instead of tkinter.filedialog.askopenfilename()
Related Topics
Performance of Pandas Apply VS Np.Vectorize to Create New Column from Existing Columns
How to Find Tag with Particular Text with Beautiful Soup
Why Does Pyimport_Import Fail to Load a Module from the Current Directory
R Expand.Grid() Function in Python
Best Way to Join/Merge by Range in Pandas
Difference Between Variables Inside and Outside of _Init_()
How to Construct a Timedelta Object from a Simple String
Installing Python Packages from Local File System Folder to Virtualenv with Pip
Django Filter Queryset _In for *Every* Item in List
Alternative to Dict Comprehension Prior to Python 2.7
Convert HTML Entities to Unicode and Vice Versa
How to Install and Import Python Modules at Runtime
Creating Same Random Number Sequence in Python, Numpy and R
Show Default Value for Editing on Python Input Possible
How to "Test" Nonetype in Python