Ronald Adams
Ronald Adams

Reputation: 31

Python Tkinter - AttributeError: 'str' object has no attribute 'read'

When I go to open a file I get the aforementioned error code "AttributeError: 'str' object has no attribute 'read'"

Any idea how to fix this? In advance I appreciate any help

Here is my code below:

import tkinter.scrolledtext as ScrolledText
from tkinter import *

root = Tk()
root.title("Diary")
root.minsize(width=400, height=400)
root.maxsize(width=800, height=480)

text= ScrolledText.ScrolledText (root, width=400, height=400)
text.pack()

def donothing():
   x = 0

def newFile():
    global filename
    filename = "Untitled"
    text.delete(0.0, END)

def openFile():
    rootFilename =  filedialog.askopenfilename(initialdir = "E:/Images",title = "choose your file",filetypes = (("Text file","*.txt"),("all files","*.*")))

    if rootFilename != None:
       contents= rootFilename.read()
       TextArea.insert('1.0', contents)
       file.close()

def saveFile():
    name = filedialog.asksaveasfile(mode = 'w',filetypes = (("Text file","*.txt"),("all files","*.*")))
    text2save = str(text.get(0.0,END))
    name.write(text2save)
    name.close

def Exit():
        root.destroy()

menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=newFile)
filemenu.add_command(label="Open", command=openFile)
filemenu.add_command(label="Save", command=saveFile)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=Exit)
menubar.add_cascade(label="File", menu=filemenu)

root.config(menu=menubar)
root.mainloop()

Upvotes: 1

Views: 962

Answers (1)

Henry Yik
Henry Yik

Reputation: 22503

You need to open the file yourself from the return string of askopenfilename.

def openFile():
    rootFilename =  filedialog.askopenfilename(initialdir = "E:/Images",title = "choose your file",filetypes = (("Text file","*.txt"),("all files","*.*")))

    if rootFilename:
        with open(rootFilename,"r") as f:
            f = f.read()
            text.insert('1.0', f)

Or what you wanted might be askopenfile instead:

def openFile():
    rootFilename = filedialog.askopenfile(initialdir="E:/Images", title="choose your file",
                                              filetypes=(("Text file", "*.txt"), ("all files", "*.*")))

    if rootFilename:
        rootFilename = rootFilename.read()
        text.insert('1.0', rootFilename)

Upvotes: 1

Related Questions