在Tkinter中保存文件对话框

Roh*_*nde 13 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()  
Run Code Online (Sandbox Code Playgroud)

fal*_*tru 27

功能名称是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.
Run Code Online (Sandbox Code Playgroud)

  • @RohitShinde,可以将索引指定为`(0.0,END)来获取整个文本,但是`(1.0,END)`是正确的指定方式.如果你想要第二行,你应该指定`2.x`,而不是`1.x`. (5认同)