Python Tkinter - 属性错误 : 'str' object has no attribute 'read'

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

最佳答案

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

关于Python Tkinter - 属性错误 : 'str' object has no attribute 'read' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55428171/

相关文章:

python - 使用 Mechanize 浏览器python查找静态字段的动态文本值

python - 在 Python 的一行中进行多次拆分

python - 在 Tkinter 中按下按钮后更新标签文本

Python tkinter : How do I 'send' to a tkname that has spaces in it

python - 使用Python的docx库,如何对表格进行缩进?

python - Haystack 简化中的数字

python - 如何在 python tkinter 中停止此函数

python - 如何打开另一个窗口并从中获取数据,然后保存到文件?

python - 使用 Tkinter 创建烟花

python - 将包含整数的数据框列转换为日期