0

I'd like to store a file. For this reason, I use filedialog with a 'with' statement. As long as I chose a file and save it, everything works fine. However, when the filedialog is canceled, I get the following error:

File "...\src\test.py", line 7, in with filedialog.asksaveasfile(mode='w') as myFile: AttributeError: enter

Is there a work arround to accomplish this with the 'with' statement?

import tkinter as tk
from tkinter import filedialog

root = tk.Tk()

with filedialog.asksaveasfile(mode='w') as myFile:
    myFile.write('Test')

root.mainloop()
Molitoris
  • 935
  • 1
  • 9
  • 31
  • Use a `try...except` block around it. When you cancel a dialog `filedialog.asksaveasfile()` returns `None` and `None` doesn't have `__enter__()` in it to handle the `with` statement. You can write your own `asksaveasfile()` method (it's just a convenience wrapper around `filedialog.SaveAs()` anyway) to return a valid `with` structure no matter what, but then `myFile` would have to be set to `None` and you would have to check it before writing to it wholly negating the purpose of the `with` statement. – zwer Jul 25 '17 at 11:57
  • Instead of editing in your answer to the question, please post it as an answer below. – Lafexlos Jul 25 '17 at 13:53

1 Answers1

1

Thanks for the clarification, zwer . I think a try...finally block is the most convenient solution for my purpose. I will overcome the problem as follows:

import tkinter as tk
from tkinter import filedialog

def Test():        
    root = tk.Tk()

    myFile = filedialog.asksaveasfile(mode='w')

    if not myFile:
        return        
    try:
        myFile.write('Test')
    finally:
        myFile.close()

    root.mainloop()


Test()
Molitoris
  • 935
  • 1
  • 9
  • 31