Skip to content Skip to sidebar Skip to footer

Disable Tkinter Keyboard Shortcut

I have an event handler that I bound to Ctrl+H, which Tkinter also recognizes as backspace. Though I read that with a return 'break' at the end of the handler I should stop the pro

Solution 1:

You probably bound CTRL+H on the root.

The reason this happens is because the event is dispatched in this order :

  1. Widget callback
  2. Widget class callback *
  3. Root callback

    *(this is where the default behavior comes from)

The solution is to bind the event twice. Once on the Text widget itself with return "break" and once on the root so that the callback is triggered with other widgets as well. The return "break" on the widget will prevent it to go to phase 2 (the next), where the undesired default behavior comes from.

You can use an utility like this one

defk(handler):
    """decorates an event handler in such a way
that the default shortcut command is not triggered
same as event.preventDefault() in HTML5 but
as a decorator"""defprevent_default(*event):
        handler(event)
        return'break'return prevent_default

related answer for more details about callback cascading disable tkinter keyboard shortcut (2)

Solution 2:

My guess is that the statement config.text.tag_add(...) is throwing an error that is not being caught. If that's the case the return statement will never execute. If the return never executes, there's nothing to prevent the class bindings from firing.

The error will be thrown if no text is selected in the window.

Post a Comment for "Disable Tkinter Keyboard Shortcut"