1

I have just started to create a simple text editor. I have already bound a couple of functions to certain keypresses and now I'm trying to add a function that operates on the Return delete being pressed. The aim is to remove the last character entered into the text widget. Here is my code:

from tkinter import *
from tkinter import filedialog
import os

root = Tk()
root.geometry('{}x{}'.format(500, 500))

def addchar(event):
    w.insert(END, event.char)

def deletechar(event):
    current = w.get()
    new = current[:-1]
    w.delete(0,END)
    w.insert(END, new)

def savefile(event):
    file = filedialog.asksaveasfilename(defaultextension=".txt")
    if file is None:
        return
    text2save = str(w.get())
    file.append(data)
    file.close()


 w = Entry(root, bd=1)
 w.pack()
 w.place(x=0, y=0, width=500)
 root.bind("<Key>", addchar)
 root.bind("<BackSpace>", deletechar)
 root.bind("<Control-s>", savefile)
 root.bind("<Return>", newline)

 root.mainloop()

The issue I'm having is that nothing is removed upon pressing delete to remove the last character entered. Any help appreciated. P.S. Ive tried adding a savefile function to save the text to a file but it doesn't work if anyone can help there also, it would again be appreciated :)

Dylan Haigh
  • 53
  • 1
  • 9

1 Answers1

0

I didn't try to run your code right know because I'm running out of time. However, first of all, you should not use pack and place geometry manager in the same Toplevel, you should only use one. Second, in your savefile function, you did not open the file, so your file variable is only a string. You should use something like file = open(file).

Mia
  • 2,466
  • 22
  • 38