Search code examples
tkinterfiledialog

Why do I receive a file not found error when using askopenfilename() with Tkinter on Mac?


I've been following a Codemy tutorial on YouTube showing how to create a basic text editor. The tutorial is created using Python on Windows. I'm using a Mac.

The program works for the guy in the tutorial but I cannot find a solution to my error anywhere. Does anyone have any ideas that could point me toward a solution? It seems like the program should work to me.

Thanks!

Here is the code. The file dialog box appears and allows me to choose a text file.

def open_txt():

text_file = filedialog.askopenfilename(initialdir="/", title="Select a File", filetypes=[("Text Files", "*.txt")])
   text_file1 = open("text_file", "r") # opens file
   contents = text_file1.read() # reads data and stores in contents variable
   my_textbox.insert(END, contents) # dispays contents in textbox
   text_file.close() # closes txt file

The problem is when I click to select the text file I receive this error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/tkinter/__init__.py", line 1921, in __call__
    return self.func(*args)
  File "/Users/ggill/PycharmProjects/Tkinter_Lessons/11_Choosing_a_textfile.py", line 13, in open_txt
    text_file1 = open("text_file", "r") # opens file
FileNotFoundError: [Errno 2] No such file or directory: 'text_file'

Solution

  • change this line:

    text_file1 = open("text_file", "r") # opens file
    

    to the line below:

    text_file1 = open(text_file, "r") # opens file
    

    cause text_file is a variable not a string.

    have fun :)