正在获取“ FileNotFoundError:[Errno 2]没有此类文件或目录”

时间:2019-11-23 22:15:05

标签: python tkinter import

由于遇到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)   open_note中的文件“ C:/ Users / user / Documents / Pythonscript / Notepad / tkinter Vers2.py”,第21行     file_obj =打开(file_path) FileNotFoundError:[错误2]没有这样的文件或目录:

1 个答案:

答案 0 :(得分:0)

您在评论中说,仅当您关闭对话框而不选择文件时,才会发生这种情况。在这种情况下,对话框函数旨在返回空字符串。

如果openf为空,您只需要解决这个问题并从函数返回而不加载就可以了,因为没有要加载的内容。