如何使用要突出显示的文本索引而不是 line.col tkinter 索引突出显示 tkinter 文本小部件中的一段文本

How do I highlight a section of text in a tkinter text widget using the index of the text to be highlighted rather than the line.col tkinter index

我正在尝试突出显示 tkinter 文本小部件中的一部分文本。如果您知道要突出显示的文本的 line.col 索引,这很容易做到。但是,我想强调的文本部分的索引是典型的字符串索引格式(整数),而不是 tkinter 要求的 line.col 索引格式。下面是一些简化的代码,显示了我要完成的工作:

from tkinter import *

class textHighlightWidget(Frame):
   def __init__(self, parent=None):
       Frame.__init__(self, parent)
       self.pack(expand=YES, fill=BOTH)
       self.makeWidgets()

    def text_for_widget(self):
        return 'This is a cat. This is a dog \n This is a cat and a 
dog. \n' \
               'This is a horse'

    def highlight_text_index(self):
        sent_beg_index = 20
        sent_end_index = 40
        self.text1.tag_add('sel', sent_beg_index, sent_end_index)

    def highlight_text_line_col(self):
        sent_beg_index = '1.0'
        sent_end_index = '2.5'
        self.text1.tag_add('sel', sent_beg_index, sent_end_index)

    def highlight_text_convert_index(self):
        sent_beg_index = 20
        sent_end_index = 40
        formatted_sent_beg_index = self.text1.index(sent_beg_index)
        formatted_sent_end_index = self.text1.index(sent_end_index)
        self.text1.tag_add('sel', formatted_sent_beg_index, 
formatted_sent_end_index)

    def makeWidgets(self):
        #self.btn1 = Button(self, text='Highlight Text', 
command=self.highlight_text_index)
        #self.btn1 = Button(self, text='Highlight Text', 
command=self.highlight_text_line_col)
        self.btn1 = Button(self, text='Highlight Text', 
command=self.highlight_text_convert_index)
        self.btn1.grid(row=0, column=0)
        self.text1 = Text(self, height=4, width=30)
        self.text1.tag_configure("center", justify='center')
        self.text1.insert('end', self.text_for_widget(), 'center')
        self.text1.grid(row=0, column=1)


if __name__ == '__main__':
    root = Tk()
    app = textHighlightWidget(root)
    root.mainloop()

我有三个不同的 highlight_text defs。第一个 (highlight_text_index) 仅使用我要突出显示的文本部分的开始和结束字符的整数索引。当我 运行 使用此 def 的代码时,出现以下错误:

_tkinter.TclError: bad text index "20"

第二个 highlight_text def (highlight_text_line_col) 使用 tkinter 期望的 line.col 格式。此方法突出显示文本的指定部分,但我不知道如何将我的整数索引转换为 line.col 索引格式,因此第二个 highlight_text def 仅向我显示 tag_add 命令是使用正确的命令,但不允许我 select 我想要突出显示的文本部分。

第三个highlight_text def (highlight_text_convert_index) 使用tkinter 的文本索引方法将索引转换为tkinter 期望的line.col 格式。在我看来,这应该可以工作,但我再次收到与第一个 highlight_text def:

相同的错误消息
_tkinter.TclError: bad text index "20"

如果有人知道如何在 tkinter 文本小部件中突出显示文本直接形成索引的整数形式或如何将索引转换为 line.col 格式 tkinter 期望我将不胜感激。

您必须为文本小部件使​​用 line.col 格式。但是,文本小部件支持对基本索引进行修改。例如,您可以添加 + <n> characters"(或更短的 +<n>c)以计算距离基本索引 个字符的位置。

因此,如果您想使用像“20”这样的传统字符串索引,您可以使用 "1.0+20c" 来获取第 20 个字符。