Tcl / Tk:突出显示文本小部件中的某些行或更改特定行文本的颜色

时间:2015-04-28 06:29:18

标签: text tcl tk

我想为我的Tcl / Tk工具实现一个效果:在text小部件中,根据具体情况,我希望突出显示一些行'背景颜色,其他线条正常透明。有可能吗?
我尝试了一些选项,例如:-highlightbackground-insertbackground等,但没有人可以做到这一点。
如果这是不可能的,如何更改指定行文本的颜色,它也是一种解决方法。

2 个答案:

答案 0 :(得分:4)

  

我希望突出一些线条的背景颜色,其他线条是正常和透明的。有可能吗?

是。您可以通过在相关文本上设置标记来实现。然后,您可以使用该标签配置文本以查看您希望的方式,包括更改字体,前景色和背景色。在插入文本或使用tag add方法时设置标记。标签使用tag configure方法进行配置。

# Make a text widget and put some text in it
pack [text .t  -height 10  -width 40]
.t insert  1.0  "This is an example of tagging."

# Set some tags; they have no style as yet
.t tag add  foo  1.5 1.10
.t tag add  bar  1.15 1.20

# Configure the tags so that we can see them
.t tag configure  foo  -font {Times 16 {bold italic}}
.t tag configure  bar  -foreground yellow  -background blue

请注意,选择实际上是一个特殊标记sel。您可以根据需要对其进行配置,但文本小部件的类绑定控制应用它的位置以响应用户操作。

答案 1 :(得分:3)

您可以使用Tk小部件演示来帮助您,更具体地说是搜索工具。在这里,我将其中最基本的部分用一些编辑来简化它:

package require Tk

# proc to highlight
proc textSearch {w string tag} {
  # Remove all tags
  $w tag remove search 0.0 end
  # If string empty, do nothing
  if {$string == ""} {return}
  # Current position of 'cursor' at first line, before any character
  set cur 1.0
  # Search through the file, for each matching word, apply the tag 'search'
  while 1 {
    set cur [$w search -count length $string $cur end]
    if {$cur eq ""} {break}
    $w tag add $tag $cur "$cur + $length char"
    set cur [$w index "$cur + $length char"]
  }
  # For all the tagged text, apply the below settings
  .text tag configure search -background blue -foreground white
}


# Window set ups    
text .text -yscrollcommand ".scroll set" -setgrid true
scrollbar .scroll -command ".text yview"

frame .string
label .string.label -text "Search string:" -width 13 -anchor w
entry .string.entry -width 40 -textvariable searchString
button .string.button -text "Highlight" \
    -command "textSearch .text \$searchString search"

pack .string.label .string.entry -side left
pack .string.button -side left -pady 5 -padx 10
bind .string.entry <Return> "textSearch .text \$searchString search"

pack .string -side top -fill x
pack .scroll -side right -fill y
pack .text -expand yes -fill both

.text insert 1.0 \
{Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce aliquet, neque at sagittis vulputate, felis orci posuere sapien, a tempus purus diam id tellus. Quisque volutpat pretium iaculis. Mauris nibh ex, volutpat id ligula sit amet, ullamcorper lobortis orci. Aliquam et erat ac velit auctor bibendum. Aliquam erat volutpat. Maecenas fermentum diam sed convallis fermentum. Maecenas ultricies nisi mauris, ac lacinia lacus sollicitudin eget. Mauris eget euismod nisi, sed suscipit est.}
相关问题