Search code examples
pythontkintertkinter-button

How to allow the user to select both files and folders in tkinter python


def browse_file(self):
    file_path = filedialog.askopenfilename(filetypes=[("All Files", "*.*")])
    if file_path:
        self.localPath.delete(0, tk.END)
        self.localPath.insert(tk.END, file_path)

The function above allows users to select the file from the dialog box, but i wanted to allow the user to select either folder or file.

I want a method that can allow a user to select either file or folder when the function is called


Solution

  • You can check whether the input is filename or directory. Here is the sample code:

    def browse_file_or_folder():
        file_path = filedialog.askopenfilename(filetypes=[("All Files", "*.*")])
        if not file_path:
            folder_path = filedialog.askdirectory()
            if folder_path:
                # Handle the selected folder path
                print("Selected folder:", folder_path)
        else:
            # Handle the selected file path
            print("Selected file:", file_path)
            self.localPath.delete(0, tk.END)
            self.localPath.insert(tk.END, file_path)