Python Forum
[Tkinter] cancelling open dialog gives empty string - 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] cancelling open dialog gives empty string (/thread-34150.html)



cancelling open dialog gives empty string - rwahdan - Jul-01-2021

Hi,

I am trying to open a file using the file dialog but what if the user decides to press cancel? a new line is added to my text widget. I don't want that extra line added there, how to achieve that?

text_file = filedialog.askopenfilename(initialdir="C:/Documents", title="Open File",
        filetypes=(("Text Files", "*.txt"),("HTML Files", "*.html"),
                   ("Python Files", "*.py"), ("All Files","*.*")))

    if (len(text_file) !=0):
        my_text.delete("1.0", END)
        open_status_name = text_file
        name, file_extension = os.path.splitext(text_file)
        name = name.split('/')[-1].split('.')[0]
        root.title(name+file_extension)
        status_bar.config(text = "File Opened Successfully!        ")
        text_file = open(text_file,"r")
        stuff = text_file.read()
        my_text.insert(END, stuff)
        text_file.close()
   else:
what i need to do in the else statement to delete that extra line because the user cancelled the operation?

Thanks


RE: cancelling open dialog gives empty string - deanhystad - Jul-01-2021

Prefix your question with what GUI you are using. Better yet, make your example code complete so others can run it.

I don't see where you are adding anything to a text widget if text_file is empty.


RE: cancelling open dialog gives empty string - steve_shambles - Jul-17-2021

Assuming this code is in a function (it probably should be), then;

if text_file = "":
    return
after the filedialog line.


(Jul-01-2021, 01:04 PM)rwahdan Wrote: Hi,

I am trying to open a file using the file dialog but what if the user decides to press cancel? a new line is added to my text widget. I don't want that extra line added there, how to achieve that?

text_file = filedialog.askopenfilename(initialdir="C:/Documents", title="Open File",
        filetypes=(("Text Files", "*.txt"),("HTML Files", "*.html"),
                   ("Python Files", "*.py"), ("All Files","*.*")))

    if (len(text_file) !=0):
        my_text.delete("1.0", END)
        open_status_name = text_file
        name, file_extension = os.path.splitext(text_file)
        name = name.split('/')[-1].split('.')[0]
        root.title(name+file_extension)
        status_bar.config(text = "File Opened Successfully!        ")
        text_file = open(text_file,"r")
        stuff = text_file.read()
        my_text.insert(END, stuff)
        text_file.close()
   else:
what i need to do in the else statement to delete that extra line because the user cancelled the operation?

Thanks