2017-05-24 5 views
1

私は現在、メインのtextBoxを検索し、検索に一致する単語を強調表示するウィジェットを持っています。私が実行している問題は、最初に見つかったマッチにカーソルを移動し、次回にenterを押したときに見つかった次のマッチにカーソルを移動する方法を見つけることです。単語のテキストボックスにアクセスし、テキストボックスの次の一致にカーソルを移動しますか?

私はテキストボックスで単語を検索できる2つの方法があります。

1つの方法は、すべての一致を検索し、検索する単語のフォント、色、サイズを変更して、残りのテキストから目立つようにすることです。ここで私がそのために使う関数です。

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') 

私が試した他の方法は、検索対象の単語のすべての一致を強調表示することです。ここにその機能があります。私はこの方法を使用している第2の方法では

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を( 『挿入』)」と私はそれだけで見つかった最初の試合に私を移動します気づきました。私は次の試合にカーソルを移動するために何をすべきかについて悩んでいます。

カーソルと画面を次の一致に移動しながら、Enterキーを何度も押してリストを下に移動したいと考えています。

多分私はここで単純なものが欠けているかもしれませんが、私は固執しており、どうすればこの問題に対処するべきかわかりません。私はウェブで答えを探すのにかなりの時間を費やしましたが、私がやろうとしていることをすることはできませんでした。私が見つけたすべてのスレッドは、すべての単語を強調表示することに関連しており、それはそれです。

答えて

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を使用して次のタスクを実行できます。私はaltを逆にしてバインドできると確信しています。ありがとう。 –

関連する問題