【发布时间】:2019-02-13 17:11:37
【问题描述】:
我正在尝试突出显示 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 命令是正确使用的命令,但不允许我选择我想要的文本部分进行突出显示。
第三个 highlight_text def (highlight_text_convert_index) 使用 tkinter 的 text index 方法将索引转换为 tkinter 期望的 line.col 格式。在我看来,这应该可以工作,但我再次收到与第一个 highlight_text def 相同的错误消息:
_tkinter.TclError: bad text index "20"
如果有人知道如何直接在索引的整数形式中突出显示 tkinter 文本小部件中的文本,或者如何将索引转换为 line.col 格式,tkinter 希望能得到帮助。
【问题讨论】:
标签: python-3.x tkinter widget highlight