Ask Your Question

Revision history [back]

To use Tkinter's filedialog to choose folders and files, you can follow these steps:

  1. Import the necessary modules:
from tkinter import *
from tkinter import filedialog
  1. Create a tkinter window or root:
root = Tk()
  1. Define a function to open the file dialog box and get the path of the selected folder or file:
def open_file_dialog():
    path = filedialog.askopenfilename()  # to get files
    # path = filedialog.askdirectory()  # to get folders
    print(path)
  1. Create a button in the tkinter window or root and assign the above function as its command:
btn = Button(root, text="Open File Dialog", command=open_file_dialog)
btn.pack()
  1. Start the tkinter's mainloop:
root.mainloop()

This will create a button called "Open File Dialog" and when you click on it, the file dialog box will open and allow you to choose the desired folder or file. The path of the selected folder or file will then be printed on the console.