2014-07-18 44 views
0

我是python的新手。我正在使用Tkinter製作用戶界面。 我有一個文本框,其中用戶可以寫入多行。 我需要在該行中搜索某些單詞並突出顯示它。如何獲得在tkinter文本框中搜索的單詞的索引

當前當我在其中搜索所需的單詞並嘗試使用「tag_configure」和「tag_add」進行着色時,出現錯誤「不良索引」。 在網上閱讀某些網頁後,我才知道,「tag_add」中使用的開始和結束索引的格式爲「row.column」[如果我在某處出錯,請糾正我的錯誤]。任何人都可以幫助我從tkinter ui直接獲取這種格式的索引來突出顯示。

+0

爲什麼不告訴我們原始的錯誤消息?和你的代碼? –

+0

請參見[解釋Tkinter文本搜索方法](http://stackoverflow.com/a/19466754/1832058) – furas

回答

-1

它必須是浮點數 - 適用於文本例如第一個字符是1.0(不串"1.0"


編輯:我犯的錯誤。它可以是字符串 - 它必須是字符串,因爲1.11.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

+0

您的聲明「它必須是浮點數」不正確。它不是一個浮點數,它是一個「line.character」形式的字符串。它可能看起來像一個浮點數,但事實並非如此。例如,浮點數1.1和1.10表示相同的數字,但它們不代表文本小部件中的相同字符。 –

+0

你是對的 - 現在我看到我的錯誤'1.1和1.10' - 我總是使用float,但只有'1.0'來清除所有文本。 – furas

+0

感謝所有.. 我能夠在這篇文章的幫助下做到這一點.. http://stackoverflow.com/questions/3732605/advanced-tkinter-text-box – TheUser

相關問題