3

In other words if I pass off the folder to someone containing a .txt and .py, and the script is run on their machine from this folder, how can I ensure the file dialog will open with this folder to select the .txt without knowing the absolute path? Referring to initialdir=??

from tkinter import filedialog
from tkinter import *

root = Tk()
root.withdraw()
root.filename = filedialog.askopenfilename(initialdir='/python', title="Select file",
                                           filetypes=[("Text Files", "*.txt")])
print(root.filename)

1 Answer 1

8

You should use the os module and os.getcwd() to find the current working directory of the .py file

import os
from tkinter import filedialog
import tkinter as tk

root = tk.Tk()
root.withdraw()
root.filename = filedialog.askopenfilename(initialdir=os.getcwd(), title="Select file",
                                           filetypes=[("Text Files", "*.txt")])
print(root.filename)

I would also suggest doing import tkinter as tk instead as importing everything may lead to naming conflicts if you are not careful, plus it's much easier to determine that what you are referring to came from the tkinter module when you prefix it with tk

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.