【发布时间】:2017-02-13 20:26:50
【问题描述】:
我正在制作一个索引工具,我想用颜色突出显示所有结果。在下面的代码中,它仅适用于第一行。当有新行时,标签将中断。例如,当我在下面的字符串中搜索单词“python”时,标签只突出显示第一行。它不适用于第二行和第三行。请帮帮我。
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()
【问题讨论】: