1

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 !

Deepak pal
  • 61
  • 8

2 Answers2

2

Canvas a method called dchars() which you can use to delete characters of canvas text.

syntax: canvas.dchars(tagOrId, first, last)

dchars deletes characters from a text item or items. you can specify from which index you want you delete. For example, canvas.dchars(tag, 1, 3) will remove the second, third and fourth characters.

To delete the last character of the text use canvas.index(tagOrId, specifier) to get the index of the last character. The specifier tkiner.END returns the last index of the string, then use dchars as shown below.

from tkinter import *

def update(event):
     canvas.dchars('text', canvas.index('text' ,END)-1 )
    

window = Tk()
canvas = Canvas(window,width=300, height=300, bd=0)
canvas.pack()

canvas_textbox = canvas.create_text(20, 70, text='Text', fill="red", tag='text')
canvas.bind('<Button>', update)

window.mainloop()
JacksonPro
  • 3,135
  • 2
  • 6
  • 29
1

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()
Thingamabobs
  • 7,274
  • 5
  • 21
  • 54