Tcl / Tk - 无法将类方法作为按钮命令附加

时间:2016-08-16 17:48:13

标签: tcl tk itcl

我试图将方法附加到命令按钮但是收到以下错误消息。如果我附上过程,它的工作正常。

怎么做?

% itcl::class a { 
    method test {} {puts test}
    constructor {} {
        button .t.b -command test; 
        grid config .t.b -column 0 -row 0
    } 
}

% a A

invalid command name "resize"
invalid command name "resize"
    while executing
"resize"
    invoked from within
".t.b invoke"
    ("uplevel" body line 1)
    invoked from within
"uplevel #0 [list $w invoke]"
    (procedure "tk::ButtonUp" line 24)
    invoked from within
"tk::ButtonUp .t.b"
    (command bound to event)

2 个答案:

答案 0 :(得分:2)

按钮回调在全局上下文中处理,因为按钮不知道itcl类,回调发生在类不在执行堆栈上时。这意味着回调需要使用允许外部代码调用方法的其中一种形式:

# The form with "$this test" is not preferred as it can go wrong with complex data.
# It tends to show up when you tidy things up for a demo! Using [list] avoids trouble.
button .t.b -command [list $this test]
# The [namespace code] command picks up the current namespace context. That's what itcl
# needs to work correctly.
button .t.b -command [namespace code { test }]

答案 1 :(得分:0)

好的 - 所以"这个"诀窍

% itcl::class a { 
    method test {} {puts test}
    constructor {} {
        button .t.b -command "$this test"; 
        grid config .t.b -column 0 -row 0
    } 
}