Search code examples
pythonpython-3.xtkinterdiacriticstkinter-entry

How to get a binded key not to type into Entry box


I have a program in which I want to type in, for example, ĝ when g^ is typed in an Entry box. I have got the ĝ to appear, but seem unable to rid the entry box of the ^ that has been typed in (yes, I have tried to use the delete function). As far as I can work out, the ^ isn't typed out until after the binded functions have occurred, meaning that if I try and index "^" or "/", it hasn't actually been typed out yet.

from tkinter import *
tk = Tk()
entry = Entry(tk)
entry.pack()
entry.bind("^", lambda x: accent(entry, "^"))
entry.bind("/", lambda x: accent(entry, "/"))

def accent(object, accent):
    global entry
    letter = entry.get()[len(entry.get())-1]
    entry.delete((len(entry.get())-1), len(entry.get()))
    if accent == "^":
        if letter == "a":
            entry.insert(END, "â")
        if letter == "g":
            entry.insert(END, "ĝ")
    if accent == "/":
        if letter == "a":
            entry.insert(END, "á")

Solution

  • Your binding needs to return "break", which tells tkinter to stop any further processing of the event. Returning "break" will prevent the character from being inserted.