简体   繁体   中英

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.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM