Search code examples
pythonpython-3.xtkinterttktkinter-entry

Python tkinter - ttk - bind - Replace pressed character with another one


I want to write in a TTK entry a specific character when a key is pressed, removing from the entry the character related to that specific key.

For example:

If I press * I want that in the entry is entered × and not ×* like how I tried to do this (see below)

At the moment I did this but it's not working as expected (in this extract there aren't the imports and Window is not defined):

def writeToEntry(text, delete=False):
    if delete:
        e.delete(0, END)
    e.insert(END, text)
    e.focus_set()

e = Entry(w)
e.grid(row=0, column=0, columnspan=3, sticky="nsew")
e.bind('*', lambda event: writeToEntry("×"))
e.bind('/', lambda event: writeToEntry("÷"))

Could you please help me? Thanks


Solution

  • You simply need to return the string "break" to prevent the original character from being inserted.

    def writeToEntry(text, delete=False):
        if delete:
            e.delete(0, END)
        e.insert(END, text)
        e.focus_set()
        return "break"