Re-binding “select all” in Text widget

前端 未结 2 2029
时光取名叫无心
时光取名叫无心 2021-02-14 04:12

I\'m working with the Text widget and I have an issue about old-school shortcuts that Tk uses.

Ie:

Select all: Ctrl + / vs Ctrl + a

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-14 05:07

    The default bindings are applied to the widget class. When you do a bind, it affects a specific widget and that binding happens before the class binding. So what is happening is that your binding is happening and then the class binding is happening, which makes it seem as if your binding isn't working.

    There are two ways to solve this. One, your ctext_selectall can return the string "break" which will prevent the class binding from firing. That should be good enough to solve your immediate problem.

    The second solution involves changing the class binding so that your preferred binding applies to all text widgets. You would do this using the bind_class method.

    Here's an example of rebinding the class:

    def __init__(...):
        self.root.bind_class("Text","", self.selectall)
    
    def selectall(self, event):
        event.widget.tag_add("sel","1.0","end")
    

    effbot.org has a pretty decent writeup titled Events and Bindings. It goes into a little more detail about class and widget bindings and the order in which they occur.

    Tk's binding mechanism is about the best of any GUI toolkit there is. Once you understand how it works (and it's remarkably simple) you'll find it's easy to augment or replace any or all of the default bindings.

提交回复
热议问题