在 Tkinter 中保存文件对话框 [英] Save File Dialog in Tkinter
问题描述
我正在用 python 实现一个基于 GUI 的文本编辑器.
我已经显示了文本区域,但是当我尝试在 Tkinter 中使用 asksaveasfile 方法时,它显示该文件已被保存,但是当我尝试在我的桌面编辑器中打开同一个文件时,它给了我一个空白文件.
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()
推荐答案
函数名是asksaveasfilename
.它应该被限定为 tkFileDialog.asksaveasfilename
.并且它不接受 mode
参数.
The function name is asksaveasfilename
. And it should be qualified as tkFileDialog.asksaveasfilename
. And it does not accept mode
argument.
也许您想使用 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.
这篇关于在 Tkinter 中保存文件对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!