它必須是浮點數 - 適用於文本例如第一個字符是1.0
(不串"1.0"
)
編輯:我犯的錯誤。它可以是字符串 - 它必須是字符串,因爲1.1
和1.10
是相同的浮點數(如說Bryan Oakley) - 但我留下了這個工作示例。
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](https://i.stack.imgur.com/gM1Ev.png)
爲什麼不告訴我們原始的錯誤消息?和你的代碼? –
請參見[解釋Tkinter文本搜索方法](http://stackoverflow.com/a/19466754/1832058) – furas