0

在创建基于 GUI 的文本编辑器时,我使用打开文件对话框打开文件。

但是,我发现每当我选择要打开的文件时,它都会读取它并在文本区域显示垃圾。更具体地说,它显示数字.140598120872128

为什么会发生这种情况,我该如何纠正?

这是我的代码。我做错什么了吗?

from Tkinter import *
import tkMessageBox
import Tkinter
import tkFileDialog

def donothing():
   print "a"

def file_save():
    name=tkFileDialog.asksaveasfile(mode='w',defaultextension=".txt")
    if name is None:
        return
    text2save=str(text.get(0.0,END))
    name.write(text2save)
    name.close()

def file_open():
    ftypes = [('Text files', '*.txt'), ('All files', '*')]
    dlg = tkFileDialog.Open(filetypes = ftypes)
        fl = dlg.show()

        if fl != '':
            txt = readFile(fl)
            text.insert(END, text)

def readFile(filename):

        f = open(filename, "r")
        text = f.read()
        return text


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=file_open)
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

4

简单的错字:text是文本小部件对象。应该是txt

替换以下行:

    text.insert(END, text)

和:

    text.insert(END, txt)
于 2013-10-20T11:07:21.527 回答