alessandro
alessandro

Reputation: 3984

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 propagation of the shortcut, it doesnt work! Is it a Ctrl+H problem, or what?

Here's the code:

def setheading(event=None):
    x=tkSimpleDialog.askstring('Set as header line', 'Enter an integer 1-5: ')
    config.text.tag_add('h'+x, SEL_FIRST,SEL_LAST)
    return 'break'

Upvotes: 2

Views: 1372

Answers (2)

Walle Cyril
Walle Cyril

Reputation: 3247

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

def k(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"""
    def prevent_default(*event):
        handler(event)
        return 'break'
    return prevent_default

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

Upvotes: 1

Bryan Oakley
Bryan Oakley

Reputation: 385950

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.

Upvotes: 0

Related Questions