Version 2 of Searching in a text widget

Updated 2006-11-28 12:07:25 by suchenwi

Richard Suchenwirth 2006-11-28 - Here is example code for searching substrings in a text widget. When an instance is found, it is highlighted with the given tag. At end of the text content, the search wraps around. The global variable status reports the position of a found substring.

 proc find {w what tag} {
    foreach {from to} [$w tag ranges $tag] {
        $w tag remove $tag $from $to
    }
    set pos [$w search -count n -- $what insert+2c]
    if {$pos eq ""} {
        set ::status "not found: $what"
    } else {
        set ::status "found at $pos: $what"
        $w mark set insert $pos
        $w see $pos
        $w tag add $tag $pos $pos+${n}c
    }
 }

# Demo with an entry for the search term, a text, and a label for the status string:

 package require Tk

 pack [entry .e -textvariable Find] -fill x
 bind .e <Return> {find .t $Find hilite}

 pack [text .t -wrap word]
 .t tag configure hilite -background orange

 pack [label .l -textvariable status] -anchor w

See also Simple search and replace


Category Example