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'
You probably bound CTRL+H on the root.
The reason this happens is because the event is dispatched in this order :
- Widget callback
- Widget class callback *
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)
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.
精彩评论