2

i am new to python. i was making ui using Tkinter. i have a text box in which user can write multiple lines. i need to search in that lines for certain words and highlight it.

currently when i am searching the desired word in it and trying to color using "tag_configure" and "tag_add", i am getting error "bad index". what i came to know after reading certain pages on net is that the start and end index used in "tag_add" is 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 tkinter ui directly for highlighting.

TheUser
  • 119
  • 1
  • 1
  • 10

1 Answers1

7

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
  • 119,752
  • 10
  • 94
  • 135
  • 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