gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:08:09 28 4
gpt4 key购买 nike

当我打开文件时,我收到上述错误代码“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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com