2017-02-13 15 views
1

私はコンコーダンスツールを作っており、すべての結果を色で強調したいと思います。下のコードでは、1行目のみで動作します。新しい行があるときにタグが壊れます。たとえば、以下の文字列で 'python'という単語を検索すると、タグは最初の行のみをハイライト表示します。 2行目と3行目では機能しません。私を助けてください。tkinterテキストの新しい行にタグを追加するには?

import tkinter as tk 
from tkinter import ttk 
import re 

# ========================== 

strings="""blah blah blah python blah blah blah 
blah blah blah python blah blah blah 
blah blah blah python blah blah blah 
""" 

# ========================== 

class Application(tk.Frame): 
    def __init__(self, master=None): 
     super().__init__(master) 
     self.pack() 
     self.create_widget() 

    def create_widget(self): 
     self.word_entry=ttk.Entry(self) 
     self.word_entry.pack() 
     self.word_entry.bind('<Return>', self.concord) 

     self.string_text=tk.Text(self) 
     self.string_text.insert(tk.INSERT, strings) 
     self.string_text.pack() 

    # ========================== 

    def concord(self, event): 
     word_concord=re.finditer(self.word_entry.get(), self.string_text.get(1.0, tk.END)) 
     for word_found in word_concord: 
      self.string_text.tag_add('color', '1.'+str(word_found.start()), '1.'+str(word_found.end())) 
      self.string_text.tag_config('color', background='yellow') 


# ========================== 

def main(): 
    root=tk.Tk() 
    myApp=Application(master=root) 
    myApp.mainloop() 

if __name__=='__main__': 
    main() 

答えて

0

強調表示を追加するために使用するすべてのインデックスは、「1」で始まります。したがって、最初の文のみが強調表示されます。たとえば、行の長さが36文字の場合、「1.100」のインデックスは「1.36」とまったく同じように扱われます。

Tkinterでは、既存のインデックスに追加することで新しいインデックスを計算できるので、 "1.52"(36文字の長さのライン)ではなく "1.0 + 52chars"が必要です。例:

def concord(self, event): 
    ... 
    for word_found in word_concord: 
     start = self.string_text.index("1.0+%d chars" % word_found.start()) 
     end = self.string_text.index("1.0+%d chars" % word_found.end()) 
     self.string_text.tag_add('color', start, end) 
    ... 
+0

うわー、ブライアンオークリー、あなたに助けてくれてありがとう。それは完全に機能します。 –

関連する問題