简体   繁体   English

如何在tkinter文本中添加标签到新行?

[英]How to add tag to a new line in tkinter Text?

I'm making a concordance tool and I want to highlight all the result with colors. 我正在制作一个和弦工具,我想用颜色突出显示所有结果。 In the code below, it only works for line one. 在下面的代码中,它仅适用于第一行。 The tag will break when there is a new line. 当有新行时,标签将会中断。 For example, when I search for the word 'python' in the string below, the tag only highlight the first line. 例如,当我在下面的字符串中搜索单词'python'时,标签只突出显示第一行。 It does not work for the second and the third line. 它不适用于第二行和第三行。 Please, help me. 请帮我。

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

Every index you use to add highlighting begins with "1.", so it's always only going to highlight the first sentence. 用于添加突出显示的每个索引都以“1”开头,因此它始终只会突出显示第一个句子。 For example, if the line is 36 characters long, an index of "1.100" will be treated exactly the same as "1.36". 例如,如果行长度为36个字符,则索引“1.100”将被视为与“1.36”完全相同。

Tkinter can compute new indexes by adding to an existing index, so instead of "1.52" (for a line that is 36 characters long) you want "1.0+52chars". Tkinter可以通过添加到现有索引来计算新索引,因此不需要“1.52”(对于长度为36个字符的行),您需要“1.0 + 52chars”。 For example: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM