2

I am making a UI using tkinter. I have a text box in which the user can write multiple lines. I need to search those lines for certain words and highlight them.

Currently, when I search for a word and try to color it using tag_configure and tag_add, I get an error, "bad index".

What I've learned after reading certain pages on internet is that the start and end indices used in tag_add are those of the format row.column (please correct me if I am going wrong somewhere).

Can anyone help me in getting the index in this format from the tkinter UI directly for highlighting? Thank you in advance!

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
TheUser
  • 129
  • 1
  • 1
  • 10

1 Answers1

8

It has to be float number - for example first char in text is 1.0 (not string "1.0")


EDIT: I made mistake. It can be string - and it have to be string because 1.1 and 1.10 is the same float number (as said Bryan Oakley) - but I leave this working example.


from Tkinter import *

#------------------------------------

root = Tk()

#---

t = Text(root)
t.pack()

t.insert(0.0, 'Hello World of Tkinter. And World of Python.')

# create tag style
t.tag_config("red_tag", foreground="red", underline=1)

#---

word = 'World'

# word length use as offset to get end position for tag
offset = '+%dc' % len(word) # +5c (5 chars)

# search word from first char (1.0) to the end of text (END)
pos_start = t.search(word, '1.0', END)

# check if found the word
while pos_start:

    # create end position by adding (as string "+5c") number of chars in searched word 
    pos_end = pos_start + offset

    print pos_start, pos_end # 1.6 1.6+5c :for first `World`

    # add tag
    t.tag_add('red_tag', pos_start, pos_end)

    # search again from pos_end to the end of text (END)
    pos_start = t.search(word, pos_end, END)

#---

root.mainloop()

#------------------------------------

enter image description here

Community
  • 1
  • 1
furas
  • 134,197
  • 12
  • 106
  • 148
  • 1
    Your statement "it has to be a float number" is incorrect. It's not a floating point number, it's a string of the form "line.character". It may look like a floating pointnumber, but it's not. For example, the floating point numbers 1.1 and 1.10 represent the same number but they do _not_ represent the same character in a text widget. – Bryan Oakley Jul 18 '14 at 21:48
  • 1
    You right - now I see my mistake `1.1 and 1.10` - I always used float but only `1.0` to clear all text. – furas Jul 18 '14 at 21:54
  • 1
    thanks all.. i was able to do it with the help of this post.. http://stackoverflow.com/questions/3732605/advanced-tkinter-text-box – TheUser Jul 21 '14 at 06:30