![]() |
[Tkinter] filedialog, open a file error - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: GUI (https://python-forum.io/forum-10.html) +--- Thread: [Tkinter] filedialog, open a file error (/thread-38897.html) |
filedialog, open a file error - liketocode - Dec-07-2022 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()
RE: filedialog, open a file error - deanhystad - Dec-07-2022 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() To get this output I canceled the first selection and selected a file the second time around.
RE: filedialog, open a file error - liketocode - Dec-07-2022 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() RE: filedialog, open a file error - deanhystad - Dec-07-2022 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. RE: filedialog, open a file error - liketocode - Dec-07-2022 Agree ![]() |