大家早,
下面的代码显示了带有过程的命名空间,并且有一个名为ds_out的数组。
如果我运行此代码并按下回车按钮,我会收到错误消息:
“错误:无法读取”ds_out(0)!:没有这样的变量
如果勾选复选框并按回车键,则会显示以下消息:
“KL15是:1”,如果我取消选中该框,则会显示“KL15为:0”
如果我注释掉命名空间并且只是让程序工作正常。
有谁能告诉我为什么好吗?
namespace eval RELAY_SELECT {
tk::labelframe .rs -text "Relay Selection"
array set ds_out {
0 0
1 0
}
proc create_RS_Labels {} {
tk::label .rs.kl15_lb -text "KL15" -justify center -width 5
}
proc create_RS_CBoxes {} {
tk::checkbutton .rs.kl15_cb -width 1 -height 1 -variable kl15_cb -command {if {$kl15_cb} {
set ds_out(0) 1
set ds_out(1) 1
} else {
set ds_out(0) 0
set ds_out(1) 0
} }
}
proc create_RS_enter_Button {} {
tk::button .rs.enter -borderwidth 1 -height 1 -text "Enter" -width 5 -command {if {$kl15_cb} {
set ds_out(0) 1
set ds_out(1) 1
puts "KL15 is: $ds_out(0)"
} else {
puts "KL15 is: $ds_out(0)"
set ds_out(0) 0
set ds_out(1) 0
}
}
}
proc create_RS_LabelFrame {} {
place .rs -x 10 -y 10
grid .rs.kl15_lb -row 0 -column 0
grid .rs.kl15_cb -row 0 -column 1
grid .rs.enter -row 12 -column 0 -columnspan 6
}
create_RS_Labels
create_RS_CBoxes
create_RS_enter_Button
create_RS_LabelFrame
}
变量作用域存在问题。
始终在全局范围内评估Tk命令回调。你的数组不在全局范围内(而且像kl15_cb
这样的其他变量是全局的,尽管你可能并不期望它们是全局的)。这很快就会变得非常混乱;你强烈建议你为所有的回调做出帮助程序。这是你的代码重新设计为了理智应该如何;特别注意那里的Note!
评论。
namespace eval RELAY_SELECT {
# Note! Declare variables in namespaces, always, to avoid an obscure misfeature!
variable kl15_cb 0
variable ds_out
array set ds_out {
0 0
1 0
}
proc create_RS_Labels {frame} {
tk::label $frame.kl15_lb -text "KL15" -justify center -width 5
}
proc create_RS_CBoxes {frame} {
# Note! Fully qualified variable name!
# Note! [namespace code] to make callback script!
tk::checkbutton $frame.kl15_cb -width 1 -height 1 -variable ::RELAY_SELECT::kl15_cb \
-command [namespace code { RS_CBox_callback }]
}
proc RS_CBox_callback {} {
# Note! [variable] with *ONE* argument to bring var into procedure scope
variable kl15_cb
variable ds_out
if {$kl15_cb} {
set ds_out(0) 1
set ds_out(1) 1
} else {
set ds_out(0) 0
set ds_out(1) 0
}
}
proc create_RS_enter_Button {frame} {
tk::button $frame.enter -borderwidth 1 -height 1 -text "Enter" -width 5 \
-command [namespace code { RS_enter_callback }]
}
proc RS_enter_callback {} {
variable kl15_cb
variable ds_out
if {$kl15_cb} {
set ds_out(0) 1
set ds_out(1) 1
puts "KL15 is: $ds_out(0)"
} else {
puts "KL15 is: $ds_out(0)"
set ds_out(0) 0
set ds_out(1) 0
}
}
proc create_RS_LabelFrame {frame} {
place $frame -x 10 -y 10
grid $frame.kl15_lb -row 0 -column 0
grid $frame.kl15_cb -row 0 -column 1
grid $frame.enter -row 12 -column 0 -columnspan 6
}
tk::labelframe .rs -text "Relay Selection"
create_RS_Labels .rs
create_RS_CBoxes .rs
create_RS_enter_Button .rs
create_RS_LabelFrame .rs
}
为了我自己的理智,我也按常规缩进了所有内容。