Search code examples
pythontkinterkey-bindings

Keybinding in tkinter Python


If I type '*' in keyboard, it should be typed as 'x' in the entry field. Below is the sample code. I'm new to tkinter.

from tkinter import *
def func(number):
    x = str(e1.get())
    e1.delete(0, END)
    e1.insert(0, str(x) + str('x'))
    
main = Tk()
main.geometry('200x50')
e1=Entry()
e1.bind('*',func)
e1.pack()
main.mainloop()

Here I'm getting 'x*'. But I need only 'x' to be typed in the entry field. Any suggestions will be really helpful.


Solution

  • You need to ignore the * character entered by returning 'break' at the end of func(). Also your logic will not work if the input cursor is not at the end of the input string.

    Below is a modified func():

    def func(event):
        # add the "x" at the insertion position
        event.widget.insert('insert', 'x')
        # ignore the entered "*" character
        return 'break'