Python 在 Tkinter 中保存文件对话框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19476232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:50:55  来源:igfitidea点击:

Save File Dialog in Tkinter

pythontkinter

提问by Rohit Shinde

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.

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

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

采纳答案by falsetru

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

函数名称是asksaveasfilename. 它应该被限定为tkFileDialog.asksaveasfilename. 它不接受mode争论。

Maybe you want to use tkFileDialog.asksaveasfile.

也许您想使用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.