在创建text组件的时候,在每行的还是位置添加数字行号,初始代码如下:
proc linenums {w} {
if [llength [$w tag ranges linenum]] {
foreach {from to} [$w tag ranges linenum] {
$w delete $from $to
}
} else {
set lastline [expr int([$w index "end - 1 c"])]
for {set i 1} {$i <= $lastline} {incr i} {
$w insert $i.0 [format "%5d " $i] linenum
}
}
}
proc readfile filename {
set f [open $filename]
return [read $f][close $f]
}
pack [text .t]
.t tag configure linenum -background yellow
.t insert 1.0 [readfile [info script]]
bind .t <F1> {linenums %W}
注释:
(1)textPathName tag range tagname:返回名称为tagname的标签内容列表
(2)获取文本框内文本的行数信息:
$w tag ranges linenum
(3)文本的新信息为在每行的开始插入行号。
上述代码能够快速显示文本框内行标,但不能实时更新,随着文本的变化,改变行标的状态。
更新模式如下:
##############################
package require Tk 8.5
proc main {} {
text .text \
-wrap word \
-borderwidth 0 \
-yscrollcommand [list .vsb set]
canvas .canvas \
-width 20 \
-highlightthickness 0 \
-background white
scrollbar .vsb \
-borderwidth 1 \
-command [list .text yview]
pack .vsb -side right -fill y
pack .canvas -side left -fill y
pack .text -side left -fill both -expand true
# Arrange for line numbers to be redrawn when just about anything
# happens to the text widget. This runs much faster than you might
# think.
trace add execution .text leave [list traceCallback .text .canvas]
bind .text <Configure> [list traceCallback .text .canvas]
set f [open [info script] r]
set data [read $f]
close $f
.text insert end $data
}
proc traceCallback {text canvas args} {
# only redraw if args are null (meaning we were called by a binding)
# or called by the trace and the command could potentially change
# the size of a line.
set benign {
mark bbox cget compare count debug dlineinfo
dump get index mark peer search
}
if {[llength $args] == 0 ||
[lindex $args 0 1] ni $benign} {
$canvas delete all
set i [$text index @0,0]
while true {
set dline [$text dlineinfo $i]
if {[llength $dline] == 0} break
set height [lindex $dline 3]
set y [lindex $dline 1]
set cy [expr {$y + int($height/2.0)}]
set linenum [lindex [split $i .] 0]
$canvas create text 0 $y -anchor nw -text $linenum
set i [$text index "$i + 1 line"]
}
}
}
main
注解:
(1)行号显示部分,单独创建canves显示;