To open a file dialog in a tkinter application, tkinter provides the tkfiledialog package which creates a dialog box to interact with the external files located on the system. In order to work with filedialog, we have to first import the package using the following command,
import tkinter.filedialog as fd
To open the explorer in the window, use asopenfilename(parent, title, **options) function. It will just pull the window and allow the user to select the file from the explorer. Once the file has been opened, we can define a function to print the list of all the selected files.
# Import the required libraries from tkinter import * from tkinter import ttk import tkinter.filedialog as fd # Create an instance of tkinter frame or window win = Tk() # Set the geometry of tkinter frame win.geometry("700x350") def open_file(): file = fd.askopenfilenames(parent=win, title='Choose a File') print(win.splitlist(file)) # Add a Label widget label = Label(win, text="Select the Button to Open the File", font=('Aerial 11')) label.pack(pady=30) # Add a Button Widget ttk.Button(win, text="Select a File", command=open_file).pack() win.mainloop()
Running the above code will display a window that contains a button and a Label Text widget.
Click the Button "Select a File" to open the Dialog for selecting the Files from the Explorer.