nedla2004 nedla2004 - 18 days ago 8
Python Question

Block Normal Key Function

I am binding a normal key do run a function using Tkinter, like this:

from tkinter import *
root = Tk()
T = Text()
T.pack()
root.bind_all('h', lambda event: print('HI'))


When you press the
h
key, it prints
HI
, but also it types an
h
into the text box. Is there any easy way to block the
h
key from doing its normal purpose?

Answer

A little bit roundabout but it works.

def remove(l, i):
    n= l[:]
    n.remove(i)
    return ''.join(i for i in n)

def h_key(event):
    print('HI')
    text = T.get(1.0, 'end-1c')
    T.delete(1.0, END)
    T.insert(END, remove(list(text), 'h'))

root.bind_all('h', lambda event: h_key(event))

There is a T.config(state=DISABLED) but I could not get that to work.

state=DISABLED does block the normal key function, but doing the below:

def h_key(event):
    T.config(state=DISABLED)
    print('HI')
    T.config(state=NORMAL)

does not work for some reason.