Python tkinter text widget delete function doesn't work correctly

Question:

I am creating a calculator app and i added this backslash button to it and here is the function for the number buttons : enter image description here

it works correctly and when i press a number it just adds it to the end of the current number . and this is one of the buttons:
enter image description here

so i created the backslash function which is this :
enter image description here

but when i press it it removes the number from the beginning. as an example we have this number : 76543 , if i click on backslash it removes 7 instead of 3 and it will look like : 6543.
i tried entt.delete(-1.0) , entt.delete(END) , entt.delete(END,END) and non of them worked.
you guys know any solution?

Asked By: Decical

||

Answers:

The first argument to the delete method must be the index immediately before the character to be deleted. If you want to delete the character immediately before the insertion cursor, you can use the index "insert-1c" (the insertion point, minus one character).

entt.delete("insert-1c")
Answered By: Bryan Oakley

The Text widget is not a very good widget to use for this case. However for what you need you can use standard substrings to do the same job.

def back_slash_click():
    txt = entt.get('1.0', END)
    entt.delete('1.0', END)
    end.insert('1.0', txt[:-2])

Notes:
Text widgets automatically add ‘n‘ to the end of the get() which is why i removed 2 characters from txt.

Text.index(END) always returns the line count +1 due to the automatically added ‘n

Better Answer

The numbers for the index are line.character: it is possible to not delete and reinsert the text but you would need to get the text, count the number of lines and the number of characters in the last line then take away 2 from the final character number

You can easily find the last line with ind = int(widget.index(END))-1 and get the last line and get the amount of characters with len(widget.get(ind, END))

This can be used in this function to do the same job.

def delete_last_char(widget):
    ind = float(widget.index(END))-1.0 ##get the last line
    txt = len(widget.get(ind, END))-2 ##get the character count and -2
    rmv = float(f'{int(ind)}.{txt}') ## format this into an accepted float
    widget.delete(rmv, END) ##delete that index range from the widget
Answered By: Scott Paterson
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.