Tcl / Tk: выделите некоторую строку в текстовом виджете или измените цвет для конкретного текста строки



Я хочу реализовать один эффект для моего инструмента Tcl / Tk: в виджете text, в зависимости от конкретного условия, я надеюсь выделить цвет фона некоторых линий, другие линии являются нормальными и прозрачными. Это возможно?

Я пробовал некоторые варианты, такие как: -highlightbackground ,-insertbackground и так далее, но никто не может этого сделать.

если это невозможно, как изменить цвет текста строки specif, это также обходной путь.

537   2  

2 ответов:

Я надеюсь выделить цвет фона некоторых линий, другие линии нормальны и прозрачны. Это возможно?

Да. Вы делаете это, устанавливая тег на соответствующем тексте. Затем вы можете настроить текст с помощью этого тега, чтобы он выглядел так, как вы хотите, что может включать в себя изменение шрифта, цвета переднего плана и цвета фона. Теги устанавливаются либо при вставке текста, либо с помощью 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. Вы можете настроить его как угодно, но привязки классов текстового виджета определяют, к чему он применяется в ответ на действия пользователя.

Вы можете использовать демонстрацию виджета 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.}

Comments

    Ничего не найдено.