简体   繁体   中英

Opening a File in Tkinter gives garbage value in Text Area

While creating a GUI based text editor, I used the open file dialog box to open a file.

However, I found that whenever I select a file to open, it reads it and displays garbage on the text area. To be more specific, it displays the number .140598120872128

Why is this happening and how can I rectify it?

This is my code. Am I doing anything wrong?

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

Simple typo: text is Text widget object. It should be txt .

Replace following line:

    text.insert(END, text)

with:

    text.insert(END, txt)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM