【问题标题】:How to add tag to a new line in tkinter Text?如何在 tkinter Text 中将标签添加到新行?
【发布时间】: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() 

【问题讨论】:

    标签: python tkinter tags


    【解决方案1】:

    您用于添加突出显示的每个索引都以“1.”开头,因此它始终只会突出显示第一句。例如,如果行长 36 个字符,则索引“1.100”将被视为与“1.36”完全相同。

    Tkinter 可以通过添加到现有索引来计算新索引,因此您需要“1.0+52chars”而不是“1.52”(对于 36 个字符长的行)。例如:

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

    【讨论】:

    • 哇,非常感谢您的帮助,布莱恩·奥克利。效果很好。
    猜你喜欢
    • 2021-06-02
    • 2011-01-22
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 2015-09-16
    • 2021-04-30
    • 1970-01-01
    相关资源
    最近更新 更多