2017-05-24 43 views
1

我现在有一个小工具,将搜索我的主要的文本框,凸显符合我搜索的话。我遇到的问题是寻找一种方法来移动光标到找到的第一个比赛,随后将光标移动到下一场比赛中发现的下一次我按下回车键。SEACH文本框为一个单词,将光标移动到下一场比赛在文本框中?

我有2种方式,我可以在我的文本搜索词。

的方法之一是看每一场比赛,改变字体,颜色,被搜索的字的大小,因此它从文本的其余部分中脱颖而出。这是我使用的功能。

def searchTextbox(event=None): 
    root.text.tag_configure("search", background="green") 
    root.text.tag_remove('found', '1.0', "end-1c") 
    wordToSearch = searchEntry.get().lower() 
    idx = '1.0' 
    while idx: 
     idx = root.text.search(wordToSearch, idx, nocase=1, stopindex="end-1c") 
     if idx: 
      lastidx = '%s+%dc' % (idx, len(wordToSearch)) 
      root.text.tag_add('found', idx, lastidx) 
      idx = lastidx 
    root.text.tag_config('found', font=("times", 16, "bold"), foreground ='orange') 

我试过的另一种方法是突出显示所搜索单词的每个匹配项。这是这个功能。

def highlightTextbox(event=None): 
    root.text.tag_delete("search") 
    root.text.tag_configure("search", background="green") 
    start="1.0" 
    if len(searchEntry.get()) > 0: 
     root.text.mark_set("insert", root.text.search(searchEntry.get(), start)) 
     root.text.see("insert") 

     while True: 
      pos = root.text.search(searchEntry.get(), start, END) 
      if pos == "": 
       break  
      start = pos + "+%dc" % len(searchEntry.get()) 
      root.text.tag_add("search", pos, "%s + %dc" % (pos,len(searchEntry.get()))) 

在第二种方法我已经使用了该方法的root.text.see(‘插入’),“我已经注意到它只会动我找到的第一个匹配。为了将光标移动到下一个比赛等,我坚持要做什么。

我希望能够打回车键很多次,而移动光标,并在屏幕的下一场比赛往下移动。

也许我错过了一些简单的东西,但我卡住了,不知道该如何处理这件事。我花了大量的时间在网上搜索答案,但我找不到任何可以做我想做的事情。我发现的所有线索都与突出显示所有单词有关,就是这样。

回答

1

您可以使用文本小部件方法tag_next_rangetag_prev_range来获取具有给定标签的下一个或上一个字符的索引。然后可以将插入光标移动到该位置。

例如,假设你的比赛都有标签“搜索”,你可以实现一个“去下一场比赛”的功能像这样的东西:

def next_match(event=None): 

    # move cursor to end of current match 
    while (root.text.compare("insert", "<", "end") and 
      "search" in root.text.tag_names("insert")): 
     root.text.mark_set("insert", "insert+1c") 

    # find next character with the tag 
    next_match = root.text.tag_nextrange("search", "insert") 
    if next_match: 
     root.text.mark_set("insert", next_match[0]) 
     root.text.see("insert") 

    # prevent default behavior, in case this was called 
    # via a key binding 
    return "break" 
+0

这非常适用。我只是将这个函数添加到了我的代码中,并用'searchEntry.bind(“”,next_match)将我的输入字段绑定到了这个函数中''我应该可以在稍后将此函数添加到主要搜索函数中,可以使用Shift Enter执行下一个任务。我确信我可以绑定到相反的地方。谢谢。 –

相关问题