Python Forum
[Tkinter] filedialog, open a file error
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] filedialog, open a file error
#1
Hello

I would like to know how to avoid an error when i close the window instead of choosing a file to open.
Window that show after clicking on "open" button.

from tkinter import *
from tkinter import filedialog

def openFile():
    filepath = filedialog.askopenfilename(initialdir="C:\\Test",
                                          title="Open file okay?",
                                          filetypes=(("text files", "*.txt"),
                                          ("all files", "*.*")))
    file = open(filepath, 'r')
    print(file.read())
    file.close()

window = Tk()
button = Button(text="Open",command=openFile)
button.pack()
window.mainloop()
Error:
Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Papa Smurf\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__ return self.func(*args) File "C:/Users/Papa Smurf/PycharmProjects/Pythonbasics/test/open1.py", line 9, in openFile file = open(filepath, 'r') FileNotFoundError: [Errno 2] No such file or directory: ''
Reply
#2
Check the filepath. It will be an empty str if no file is selected.

You should answer these kinds of questions yourself. All you needed to do is set a breakpoint on line 9 and display what is returned when you cancel the file dialog. Or you could use a print statement, or you could read the documentation for the tkinter file dialog. Any of these would show you that the len(filepath)==0 when the selection is canceled.
def openFile():
    filepath = filedialog.askopenfilename(title="Open file okay?")
    print(len(filepath))

window = Tk()
button = Button(text="Open",command=openFile)
button.pack()
window.mainloop()
Output:
0 63
To get this output I canceled the first selection and selected a file the second time around.
liketocode likes this post
Reply
#3
Gee...Thx ! I'm still begginer so i miss things that are so obvious

def openFile():
    filepath = filedialog.askopenfilename(initialdir="C:\\Test",
                                          title="Open file okay?",
                                          filetypes=(("text files", "*.txt"),
                                          ("all files", "*.*")))
    if len(filepath) == 0:
        return

    file = open(filepath, 'r')
    print(file.read())
    file.close()
Reply
#4
It is exactly because you are a beginner that doing little experiments to try to understand what is happening is so important. If you dive in and figure things out for yourself your learning will progress at a much faster pace.
liketocode likes this post
Reply
#5
Agree Cool
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tkinter] Exclude hidden file, filedialog.askopenfile red380sl 1 3,188 Dec-01-2020, 07:04 PM
Last Post: DT2000
  [Tkinter] How do I open a file and the plot it? HelixFossil 3 3,590 Apr-16-2020, 03:50 AM
Last Post: HelixFossil
  [PyQt] saving text file by FileDialog option atlass218 14 4,678 Feb-19-2020, 09:22 AM
Last Post: atlass218
  [Tkinter] Unable to save filepath to config.ini file using filedialog.askopenfilename JackMack118 10 5,026 Dec-29-2019, 08:12 PM
Last Post: JackMack118
  [PyQt] I get the error when I try to open the sample Why can pyqt5 installed onatdogan 3 3,103 Dec-25-2018, 03:00 PM
Last Post: Larz60+
  [PyQt] QFSFileEngine::open: No file name specified MegasXLR 1 4,041 May-25-2018, 04:06 PM
Last Post: MegasXLR
  tkinter filedialog and pickle - custom icon question. kim07133 0 2,772 Jan-08-2018, 12:10 PM
Last Post: kim07133
  [Tkinter] filedialog. FULL SCREEN issac_n 0 3,156 Dec-05-2017, 07:33 AM
Last Post: issac_n

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020