tkinter filedialog with statement

时间:2017-07-25 11:40:55

标签: python-3.x tkinter with-statement filedialog

我想存储一个文件。出于这个原因,我使用了带有'的&。声明。只要我选择一个文件并保存它,一切正常。但是,当取消了filedialog时,我收到以下错误:

文件" ... \ src \ test.py",第7行,in 与filedialog.asksaveasfile(mode =' w')作为myFile: AttributeError:输入

是否有一项工作可以通过'来实现这一目标。声明?

import tkinter as tk
from tkinter import filedialog

root = tk.Tk()

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

root.mainloop()

1 个答案:

答案 0 :(得分:1)

感谢您的澄清,zwer。我认为一个尝试... finally块是我最方便的解决方案。我将克服这个问题如下:

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()