23

I am implementing a GUI based text editor in python.
I have displayed the text area but when I try to use the asksaveasfile method in Tkinter, it shows that the file has been saved but when I try and open the same file in my desktop editor, it gives me a blank file.

Only, the file is created and saved. Its contents are not.

I would like to know why. Am I doing something wrong? Here is my code:

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()  
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
Rohit Shinde
  • 1,575
  • 5
  • 21
  • 47

1 Answers1

45

The function name is asksaveasfilename. And it should be qualified as tkFileDialog.asksaveasfilename. And it does not accept mode argument.

Maybe you want to use 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.
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • It works. I think it was because of the parenthesis that it wasn't working. – Rohit Shinde Oct 20 '13 at 10:29
  • You just created an edit saying the indexing starts from 1.0 but my text is perfectly saved even if I put the start index as 0.0. – Rohit Shinde Oct 20 '13 at 10:30
  • 5
    @RohitShinde, It is okay to specify index as `(0.0, END) to get entire text, but `(1.0, END)` is correct to way to specify. If you want the second line, you should specify `2.x`, not `1.x`. – falsetru Oct 20 '13 at 10:31