2017-05-24 51 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執行下一個任務。我確信我可以綁定到相反的地方。謝謝。 –

相關問題