python - Tkinter 中的保存文件对话框

标签 python tkinter

我正在用 python 实现一个基于 GUI 的文本编辑器。
我已经显示了文本区域,但是当我尝试在 Tkinter 中使用 asksaveasfile 方法时,它显示文件已保存,但是当我尝试在我的桌面编辑器中打开相同的文件时,它给了我一个空白文件。

仅创建并保存文件。它的内容不是。

我想知道为什么。难道我做错了什么?这是我的代码:

from Tkinter import *
import tkMessageBox
import Tkinter
import tkFileDialog

def donothing():
   print "a"

def file_save():
    name=asksaveasfile(mode='w',defaultextension=".txt")
    text2save=str(text.get(0.0,END))
    name.write(text2save)
    name.close

root = Tk()
root.geometry("500x500")
menubar=Menu(root)
text=Text(root)
text.pack()
filemenu=Menu(menubar,tearoff=0)
filemenu.add_command(label="New", command=donothing)
filemenu.add_command(label="Open", command=donothing)
filemenu.add_command(label="Save", command=file_save)
filemenu.add_command(label="Save as...", command=donothing)
filemenu.add_command(label="Close", command=donothing)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)

editmenu=Menu(menubar,tearoff=0)
editmenu.add_command(label="Undo", command=donothing)
editmenu.add_command(label="Copy", command=donothing)
editmenu.add_command(label="Paste", command=donothing)
menubar.add_cascade(label="Edit", menu=editmenu)

helpmenu=Menu(menubar,tearoff=0)
helpmenu.add_command(label="Help",command=donothing)
menubar.add_cascade(label="Help",menu=helpmenu)

root.config(menu=menubar)
root.mainloop()  

最佳答案

函数名称是asksaveasfilename。它应该限定为 tkFileDialog.asksaveasfilename。并且它不接受 mode 参数。

也许您想使用tkFileDialog.asksaveasfile

def file_save():
    f = tkFileDialog.asksaveasfile(mode='w', defaultextension=".txt")
    if f is None: # asksaveasfile return `None` if dialog closed with "cancel".
        return
    text2save = str(text.get(1.0, END)) # starts from `1.0`, not `0.0`
    f.write(text2save)
    f.close() # `()` was missing.

关于python - Tkinter 中的保存文件对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19476232/

相关文章:

字典投影、过滤器或子集的 Python 列表?

python - 运行多个测试会在使用 @mock.patch.object 打补丁时干扰 nosetests,有时也会在使用 `with mock.patch.object` 时干扰

python - tkinter treeview - 拖放?

python - sqlite3.OperationalError...我的 sqlite 语法有什么问题?

python - 在单独的类中创建一个 tkinter 按钮

python - 加快在 python 中读取非常大的 netcdf 文件

python - 在 Python 中使 vars 在调用方法范围内可见的方法?

python - 比较 2 个 dfs 的最佳方法,获取不同 col 的名称 & before + after vals?

python - python对象之间的通信?

python - Tkinter: "Python may not be configured for Tk"