19

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

1 に答える 1

38

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.
于 2013-10-20T10:23:12.610 に答える