Search code examples
pythontkintertkinter-entry

Remove a character on the left of the cursor in Tkinter entry widget in python 3


I want to make a program in which when I click a button it clears a character left to the cursor from the entry widget.

here is what I tried:

import tkinter as tk


def clear_one(entry_field):
    from tkinter import END
    current = entry_field.get()
    current = str(current)
    cleared = current[:-1]
    entry_field.delete(0, END)
    entry_field.insert(0, cleared)


root = tk.Tk
e = tk.Entry()
e.grid(row=0, column=0)
e.focus()

b = tk.Button(text="Clear", command=lambda: clear_one(e))
b.grid(row=1, column=0)

tk.mainloop()

It just deletes the last character in the entry widget and when I move the cursor to another position and click the button it still deletes the last character in the entry widget.

But I want it to delete the character left to the cursor.

I did not find any proper solution online and it might be possible that I was unable to understand those as I'm new to programming.

Can anyone help me with this?


Solution

  • If you want to delete the character to the left of the cursor, determine the position of the cursor, subtract one, then delete that character.

    def clear_one(entry_field):
        insert = entry_field.index("insert")
        entry_field.delete(insert-1)