【问题标题】:Detect changes in a tk::text widget检测 tk::text 小部件中的更改
【发布时间】:2012-12-19 01:37:10
【问题描述】:

我想监控 tk::text 小部件中的每一个变化。

我的第一步只是获取所有<Key> 事件并将它们发送到我的监控例程,但是如果我将一些文本复制到文本小部件中,这将不起作用。

我发现了一个<Modified> 虚拟活动。这将使我能够对文本小部件中的每个更改做出反应,但我没有找到确定更改类型的方法。

对于我的实际问题,如果我将每个字符或文本都插入到我的小部件中就足够了。获取插入的位置或其他属性并不重要。

接下来我尝试绑定<Button-2> 事件。这会给我一个通知,但我无法获得插入的文本。有没有办法从 X 中获取实际选择的文本并将其复制到小部件中?这也足够了。

【问题讨论】:

    标签: widget tk


    【解决方案1】:

    如果您只想通知插入、删除和替换(所有其他修改归结为),最简单的方法是拦截 insertdeletereplace 方法。以下是使用 TclOO 包装器的方法:

    oo::class create Text {
        unexport destroy
        constructor {w} {
            rename $w [namespace current]::realwidget
            bind $w <Destroy> [namespace code {my destroy}]
        }
        self method create {w args} {
            rename [my new [::text $w {*}$args]] ::$w
            return $w
        }
    
        method DoingModification args {
            # Override this method to find out
        }
    
        method delete args {
            my DoingModification {*}$args
            tailcall realwidget delete {*}$args
        }
        method insert args {
            my DoingModification {*}$args
            tailcall realwidget insert {*}$args
        }
        method replace args {
            my DoingModification {*}$args
            tailcall realwidget replace {*}$args
        }
    }
    # Everything else should just be forwarded; there's a lot of methods to do
    # so we loop over them all...
    foreach method {
        bbox cget compare configure count debug dlineinfo dump edit get image
        index mark peer scan search see tag window xview yview
    } {
        oo::define Text forward $method realwidget $method
    }
    

    之后,您可以制作一个小部件并很容易地找出修改,否则一切都照常工作:

    set w [Text create .t]
    oo::objdefine $w method DoingModification {method args} {
        puts "Doing a $method on $args"
    }
    pack $w
    

    【讨论】:

    • 你不需要 TclOO 来做这件事——你可以用直接的 Tcl 脚本来做——但是做它的代码相当复杂;考虑在 8.5 或更早版本中使用 Snit 进行包装。
    猜你喜欢
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多