-2

I am trying to make a simple text editor with python(tkinter) in Sublime Text 3 with the following code:

from tkinter import *
from tkinter import filedialog

root=Tk()

def OpenFile():
    file_name=filedialog.askopenfilename(initialdir="/Desktop\python", title="Select a File:", filetype=(("Txt Files",".txt"),("All Files","*.*")))
    content = open(file_name).read()
    txteditor.insert(END, content)
    
def SaveFile():
    myfile = filedialog.asksaveasfile(mode='w', defaultextension='.txt')
    if myfile is None:
        return
    content=txteditor.get(1.0,'end-1c')
    myfile.write(content)

root.iconbitmap(default='icon2.ico')
root.title('My Notepad')
txteditor=Text(root, width=50, height=20).pack()

openbtn=Button(root, text='Open', command=OpenFile)
openbtn.pack()

savebtn=Button(root, text='Open', command=OpenFile)
savebtn.pack()

but when I click open button, then the window appears but when I click on open button(after selecting the file to be opened), it gives error in line 10 error I am getting when I run my code with Sublime Text 3 IDE(see in the image)

jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49
  • When I run your program, nothing happens. Please make sure the code you show does *actually create the error you are asking about*. – Jongware Jul 12 '20 at 12:12
  • I'm getting the error in txteditor.insert(END, content) only, my open file window is opening correctly with the path I mentioned with single \ – Jay Thakker Jul 17 '20 at 07:44

1 Answers1

0

The problem is with the \. The python interprets it as the escape slash - like the one used for \n swap single \ to the \\. I the error you provided you can see \ with the capital letter. The interpreter tries to escape the highlighted letter.

Aleksander Ikleiw
  • 2,549
  • 1
  • 8
  • 26
  • What backslash are you specifically talking about? The ones highlighted in the image-of-error are just the result of a dumb syntax highlighter. – Jongware Jul 12 '20 at 12:15
  • @usr2564301 no, they are not. You can paste that and you will see that it is a wrong file path. in python, the path should be determined with `\\` not with a single one. – Aleksander Ikleiw Jul 12 '20 at 12:16
  • But that path does not appear in the source code. It's in the error message. – Jongware Jul 12 '20 at 12:18
  • @AleksanderIkleiw I tried as you mentioned in your answer but it was of no help, still getting the same error – Jay Thakker Jul 12 '20 at 12:56
  • @AleksanderIkleiw I'm getting the error in txteditor.insert(END, content) only my open file window is opening correctly with the path I mentioned with single \ – Jay Thakker Jul 12 '20 at 12:59
  • im not sure, abt the error, but i believe its because, you are packing and defining in the same variable, try saying `txteditor=Text(root, width=50, height=20)` and in next line say `txteditor.pack()` – Delrius Euphoria Jul 12 '20 at 15:19