Search code examples
pythonpython-3.xtkintertkinter-canvastkinter-entry

How to delete the last character of text in canvas.create_text() in tkinter?


self.canvas_textbox = canvas.create_text(290, 250, text='SOME TEXT', anchor=NW, fill="lime")

How to delete the last character of text that is from SOME TEXT, I have to detele the last T.

I have tried the following code but it's delete the whole text.

canvas.delete(self.canvas_textbox,"1.0", END)

Please anyone help me in this !


Solution

  • To achive this you can configure the item you already have.

    For this you need first the itemcget method of the canvas, then you slice the string and insert the string via itemconfig method of the canvas.

    A working example of the use can be found here:

    import tkinter as tk
    
    def del_letter():
        old_string = canva.itemcget(c_txt, 'text')
        new_string = old_string[:-1]
        canva.itemconfig(c_txt, text=new_string)
    
    root = tk.Tk()
    canva= tk.Canvas(root)
    c_txt= canva.create_text(10,10, text='SOME TEXT', anchor='nw')
    canva.pack()
    butto= tk.Button(root, text='del last letter', command=del_letter)
    butto.pack()