我正在尝试添加一个允许我在python内置记事本中打开文本文件的功能,但是此错误显示TypeError:预期的str,字节或os.PathLike对象,而不是列表
我实际上真的是编程新手,我正在按照本教程讲解如何在python上制作记事本,我曾尝试导入os,但我不知道如何使用它。预先感谢
from tkinter import Tk, scrolledtext, Menu, filedialog, END, messagebox
from tkinter.scrolledtext import ScrolledText
from tkinter import*
#Root main window
root = Tk(className=" Text Editor")
textarea = ScrolledText(root, width=80, height=100)
textarea.pack()
# Menu options
menu = Menu(root)
root.config(menu=menu)
filename = Menu(menu)
edicion = Menu(menu)
# Funciones File
def open_file ():
file = filedialog.askopenfiles(parent=root, mode='r+', title="Select a file")
if file == None:
contenidos = file.read()
textarea.insert('1.0', contenidos)
file.close
else:
root.title(" - Notepad")
textarea.delete(1.0,END)
file = open(file,"r+")
textarea.insert(1.0,file.read)
file.close()
def savefile ():
file = filedialog.asksaveasfile(mode='w')
if file!= None:
data = textarea.get('1.0',END+'-1c')
file.write(data)
file.close()
def exit():
if messagebox.askyesno ("Exit", "Seguro?"):
root.destroy()
def nuevo():
if messagebox.askyesno("Nuevo","Seguro?"):
file= root.title("Vistima")
file = None
textarea.delete(1.0,END)
#Funciones editar
def copiar():
textarea.event_generate("<<Copy>>")
def cortar():
textarea.event_generate("<<Cut>>")
def pegar():
textarea.event_generate("<<Paste>>")
#Menu
menu.add_cascade(label="File", menu=filename)
filename.add_command(label="New", command = nuevo)
filename.add_command(label="Open", command= open_file)
filename.add_command(label="Save", command=savefile)
filename.add_separator()
filename.add_command(label="Exit", command=exit)
menu.add_cascade(label="Editar", menu=edicion)
edicion.add_command(label="Cortar", command=cortar)
edicion.add_command(label="Pegar", command=pegar)
edicion.add_command(label="Copiar", command=copiar)
textarea.pack()
#Keep running
root.mainloop()
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\57314\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:/Users/57314/PycharmProjects/text_editor/bucky.py", line 28, in open_file
file = open(file,"r+")
TypeError: expected str, bytes or os.PathLike object, not list
答案 0 :(得分:0)
您遇到此错误:TypeError: expected str, bytes or os.PathLike object, not list
这表明这一行:
file = open(file,"r+")
正在尝试打开列表。为什么会这样呢?好吧,您在此处用于分配file
变量的函数是 返回文件列表 ,而不是单个文件名:
file = filedialog.askopenfiles(parent=root, mode='r+', title="Select a file")
您是否有可能误读了本教程,您应该写的是:
file = filedialog.askopenfilename(parent=root, mode='r+', title="Select a file")
在此处查看两个功能之间的细微差别:http://epydoc.sourceforge.net/stdlib/tkFileDialog-module.html#askopenfiles。