Python Tkinter-AttributeError:“ str”对象没有属性“ read”

时间:2019-03-30 04:32:42

标签: python tkinter

当我打开文件时,出现上述错误代码“ AttributeError:'str'对象没有属性'read'”

有人知道如何解决此问题吗?预先感谢您的帮助

以下是我的代码:

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

1 个答案:

答案 0 :(得分:1)

您需要从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)

或者您想要的是askopenfile

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)