禁用 tkinter 键盘快捷键 [英] disable tkinter keyboard shortcut

查看:63
本文介绍了禁用 tkinter 键盘快捷键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个绑定到 Ctrl+H 的事件处理程序,Tkinter 也将其识别为 backspace.尽管我在处理程序的末尾使用 return 'break' 阅读了该内容,但我应该停止快捷方式的传播,但它不起作用!是 Ctrl+H 问题还是什么?

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?

代码如下:

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'

推荐答案

您可能在根目录上绑定了 CTRL+H.

You probably bound CTRL+H on the root.

发生这种情况的原因是因为事件是按以下顺序分派的:

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

  1. 小部件回调
  2. Widget 类回调 *
  3. 根回调

*(这是默认行为的来源)

*(this is where the default behavior comes from)

解决办法是将事件绑定两次.使用 return "break" 在 Text 小部件本身上一次,在根上一次,以便其他小部件也触发回调.小部件上的 return "break" 将阻止它进入第 2 阶段(下一个),这是不受欢迎的默认行为的来源.

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

有关回调级联的更多详细信息的相关答案 禁用 tkinter 键盘快捷方式(2)

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

这篇关于禁用 tkinter 键盘快捷键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆