Ask Your Question
0

How can you use Tkinter's filedialog to choose folders and files?

asked 2023-01-30 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-07-02 08:00:00 +0000

djk gravatar image

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

  1. Import tkinter and tkinter.filedialog:
import tkinter as tk
from tkinter import filedialog
  1. Create a Tkinter root window:
root = tk.Tk()
  1. To choose a folder, use the filedialog.askdirectory() function:
folder_path = filedialog.askdirectory()
  1. To choose a file, use the filedialog.askopenfilename() function:
file_path = filedialog.askopenfilename()
  1. Optionally, you can specify the initial directory, file types, and other options by passing arguments to the functions:
folder_path = filedialog.askdirectory(initialdir='/',
                                      title='Choose a folder')
file_path = filedialog.askopenfilename(initialdir='/',
                                       title='Choose a file',
                                       filetypes=[('Text Files', '*.txt'),
                                                  ('All Files', '*.*')])
  1. Finally, you can use the selected folder or file path in your code:
print(f'Selected folder: {folder_path}')
print(f'Selected file: {file_path}')
  1. Don't forget to call root.mainloop() to start the Tkinter event loop:
root.mainloop()
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-01-30 11:00:00 +0000

Seen: 11 times

Last updated: Jul 02 '21