2015-09-28 66 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 –

相关问题