【发布时间】:2020-03-19 14:52:40
【问题描述】:
收到FileNotFoundError: [Errno 2] No such file or directory 错误,不知道为什么会这样,如果有人可以帮助我,将不胜感激。
from tkinter import * from tkinter import filedialog import os from
tkinter import messagebox
os.chdir('C:\\Users\\user\\Documents\\Pythonscript\\Notepad')
def savenote():
usernotes = note_text.get("1.0", END)
result = filedialog.asksaveasfile(initialfile = 'Untitled.txt',title = 'Save your note', mode='w', defaultextension = '.txt')
if result:
result.write(usernotes)
result.close()
def open_note():
openf = filedialog.askopenfilename(initialdir =
('C:\\Users\\user\\Documents\\Pythonscript\\Notepad'), title
= ' Select Your Note', filetypes =(("Text File", "*.txt"),("All
Files","*.*")))
note_text.delete('1.0', END)
file_path = os.path.join(openf)
file_obj = open(file_path)
file_contents = file_obj.read()
note_text.insert(END, file_contents)
b = note_text.get('1.0', END)
openf.write()
openf.close()
screen = Tk() screen.title('Note App') screen.resizable
screen.geometry('800x800')
def on_closing():
if messagebox.askokcancel("Quit", "Do you want to quit?"):
screen.destroy()
screen.protocol("WM_DELETE_WINDOW", on_closing)
note_s = StringVar() Label1 = Label(screen, text = 'Write a note: ',
bg = '#a84646', fg = 'white', font=('Courier New' ,16, 'bold'),
borderwidth = 2, relief='groove', width=200, height = 2).pack()
note_text = Text(screen, height = 50, width = 270, bg = 'white',
borderwidth=2, relief= 'groove', font=(None,12), state = 'normal')note_text.pack()
menu = Menu(screen) screen.config(menu = menu)
filemenu = Menu(menu, tearoff=0) menu.add_cascade(label = 'File',menu = filemenu) filemenu.add_command(label= 'Open File', command = open_note) filemenu.add_separator() filemenu.add_command(label= 'Save File', command = savenote)
screen.mainloop()
这是我得到的错误:
Tkinter 回调异常 回溯(最近一次通话最后): 调用中的文件“C:\Users\user\AppData\Local\Programs\Python\Python37\lib\tkinter__init__.py”,第 1705 行 返回 self.func(*args) 文件“C:/Users/user/Documents/Pythonscript/Notepad/tkinter Vers2.py”,第 21 行,在 open_note file_obj = 打开(文件路径) FileNotFoundError:[Errno 2] 没有这样的文件或目录:
【问题讨论】:
-
您在哪一行收到此错误?请注意,如果您尝试加载文件,则还需要编写其后缀,例如
.txt。 -
这是整个错误:Tkinter 回调中的异常 Traceback(最近一次调用最后一次):文件“C:\Users\donovan\AppData\Local\Programs\Python\Python37\lib\tkinter_init_.py",第 1705 行,在 call 中返回 self.func(*args) 文件“C:/Users/donovan/Documents/Pythonscript/Notepad/tkinter Vers2.py” ,第 21 行,在 open_note file_obj = open(file_path) FileNotFoundError: [Errno 2] No such file or directory: ''
-
原因实际上是错误:文件不存在。您是否检查过
file_path中的值以查看它是否是您假设的值? -
只有当我点击打开文件然后实际上并没有选择文件而只是点击'x'时才会发生错误,所以我想这就是为什么它说找不到文件但它仍然很烦人错误消息。
-
是的,如果您关闭对话框而不选择文件,它将返回一个空字符串。这就是它的设计和记录方式。