重新绑定“全选"在文本小部件中 [英] Re-binding "select all" in Text widget

查看:20
本文介绍了重新绑定“全选"在文本小部件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用文本小部件,但我对 Tk 使用的老式快捷方式有疑问.

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

即:

全选:Ctrl +/ vs Ctrl + a
剪切:Ctrl + w vs Ctrl + x
复制:Meta + w vs Ctrl + c
粘贴:Ctrl + y vs Ctrl + v

Select all: Ctrl + / vs Ctrl + a
Cut: Ctrl + w vs Ctrl + x
Copy: Meta + w vs Ctrl + c
Paste: Ctrl + y vs Ctrl + v

在 Windows 上,除 Ctrl+a 外,所有这些都可以工作.

On Windows, all of them work except Ctrl+a.

1) 是否可以重定向绑定,所以 .bind('') 调用已经绑定的 Ctrl +/?

1) Is it possible to redirect binds, so .bind('<Control-a>') calls already bound Ctrl + /?

2) 我试过全选":

txt_text.bind('<Control-a>', self.ctext_selectall)

地点:

def ctext_selectall(self, callback):
    """Select all text in the text widget"""
    self.txt_text.tag_add('sel', '1.0', 'end')

但它不起作用,因为 Ctrl+a 在默认情况下起作用(光标转到开头).它与其他一些未绑定的字母一起使用.如果 1 下的解决方案是不可能的,那么有没有可能使这项工作?

But it does not work, since Ctrl+a works by default (cursor goes to the start). It function with some other, unbound, letter. Any chances of making this work if the solution under 1 is not possible?

推荐答案

默认绑定应用于小部件类.当您进行绑定时,它会影响特定的小部件,并且该绑定发生在类绑定之前.所以发生的事情是您的绑定正在发生,然后类绑定也在发生,这使得您的绑定看起来好像不起作用.

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.

有两种方法可以解决这个问题.一,您的 ctext_selectall 可以返回字符串break",这将阻止类绑定被触发.这应该足以解决您当前的问题.

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.

第二种解决方案涉及更改类绑定,以便您的首选绑定适用于所有文本小部件.您可以使用 bind_class 方法来做到这一点.

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","<Control-a>", self.selectall)

def selectall(self, event):
    event.widget.tag_add("sel","1.0","end")

effbot.org 有一篇相当不错的文章,标题为 事件和绑定.它更详细地介绍了类和小部件绑定以及它们出现的顺序.

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 的绑定机制是所有 GUI 工具包中最好的.一旦您了解了它的工作原理(而且非常简单),您就会发现增加或替换任何或所有默认绑定很容易.

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.

这篇关于重新绑定“全选"在文本小部件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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