Search code examples
pythontkintertkinter-entry

How to delete the current entry in tkinter Entry widget


I am writing a python code using tkinter to build a basic calculator. Using the Entry widget, the delete method clears all the entry in the Entry widget. How can I delete the current entry with out clearing the whole entries.

from tkinter import *
root = Tk()
entry = Entry(root)
entry.pack()
# this deletes all the entries
entry.delete(0,END)

From the doc I read about the Entry widget delete method delete(first, last=None), if the second argument is omitted, only the single entry at first position is deleted. I tried the code below, the first entry in the widget is delete.

entry.delete(0)

I tried the code below expecting that the current entry in the widget should be deleted instead it performed the same action the above performed.

entry.delete(-1)

Please what am I missing?


Solution

  • From what I can see the Entry widget does not allow negative indexes.

    But you can ask the Entry widget what index the end is at, and then delete from the last but one position:

    entry.delete(entry.index(END)-1)
    

    Will delete the last character.