Tkinter使用asksaveasfile保存文本文件

时间:2016-02-22 01:15:39

标签: python tkinter

我试图将大量变量保存到文本文档中,但是当我点击" save"当我使用asksaveasfile或asksaveasfilename时,按钮。

代码的相关部分(它选择了大约一百个不同的变量,但为了节省空间,我不会写下所有这些变量)是:

from tkinter import *
from tkinter.filedialog import *
def save_doc():
    text_file=open(asksaveasfile, mode ='w')
    text_file.write(nombrePatrocinado+"\n")
    text_file.write(apellidoPaternoPatrocinado+"\n")
    text_file.close()
saveDocBTN=Button(text="Save", command=save_doc)
saveDocBTN.grid(row=0,column=6)

当我使用它时,它说

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__
    return self.func(*args)
  File "/home/juanelo/Downloads/launcher.py", line 662, in save_doc
    text_file=open(asksaveasfile, mode ='w')

TypeError: invalid file: <function asksaveasfile at 0xb5e973d4>

我试过的另一个几乎是一样的:

from tkinter import *
from tkinter.filedialog import *
def save_doc():
    text_file=open(asksaveasfilename)
    text_file.write(nombrePatrocinado+"\n")
    text_file.write(apellidoPaternoPatrocinado+"\n")
    text_file.close()
saveDocBTN=Button(text="Save", command=save_doc)
saveDocBTN.grid(row=0,column=6)

当我尝试这个时,我得到了

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__
    return self.func(*args)
  File "/home/juanelo/Downloads/launcher.py", line 662, in save_doc
    text_file=open(asksaveasfilename)
TypeError: invalid file: <function asksaveasfilename at 0xb5df82b4>

1 个答案:

答案 0 :(得分:1)

你没有打电话给asksaveasfilename();你只是引用它。您需要添加括号:

text_file=open(asksaveasfilename())