2015-09-28 70 views
0

我正在Python 3.4和Tkinter中創建一個簡單的文本編輯器。此刻,我被卡在find功能上。突出顯示Tkinter中的某些字符

我可以找到成功的字符,但我不知道如何突出顯示它們。我試過沒有成功的標記方法,誤差:

str object has no attribute 'tag_add'. 

這裏是我的查找功能代碼:

def find(): # is called when the user clicks a menu item 
    findin = tksd.askstring('Find', 'String to find:') 
    contentsfind = editArea.get(1.0, 'end-1c') # editArea is a scrolledtext area 
    findcount = 0 
    for x in contentsfind: 
     if x == findin: 
      findcount += 1 
      print('find - found ' + str(findcount) + ' of ' + findin) 
    if findcount == 0: 
     nonefound = ('No matches for ' + findin) 
     tkmb.showinfo('No matches found', nonefound) 
     print('find - found 0 of ' + findin) 

用戶輸入文本成scrolledtext領域,我想強調的匹配該滾動文本區域上的字符串。

我該如何去做這件事?

回答

1

使用tag_add爲區域添加標籤。此外,您可以使用小部件的search方法,而不是獲取所有文本並搜索文本。我將返回匹配的開始,並且還可以返回匹配的字符數。然後您可以使用該信息添加標籤。

這將是這個樣子:

... 
editArea.tag_configure("find", background="yellow") 
... 

def find(): 
    findin = tksd.askstring('Find', 'String to find:') 

    countVar = tk.IntVar() 
    index = "1.0" 
    matches = 0 

    while True: 
     index = editArea.search(findin, index, "end", count=countVar) 
     if index == "": break 

     matches += 1 
     start = index 
     end = editArea.index("%s + %s c" % (index, countVar.get())) 
     editArea.tag_add("find", start, end) 
     index = end 
+0

我怎麼會去的功能刪除高亮顯示? –

+1

@le_wofl:http://effbot.org/tkinterbook/text.htm#Tkinter.Text.tag_remove-method –

相關問題