gpt4 book ai didi

Python Tkinter 更改某些文本范围的文本背景

转载 作者:行者123 更新时间:2023-12-01 04:11:00 25 4
gpt4 key购买 nike

我有一个很长的文本,我想通过给定的偏移量突出显示一些跨度。我如何使用 Tkinter 实现这一目标?

为了使其更具体,请考虑以下事项:

from Tkinter import *
example = """Contrary to popular belief, \n\n Lorem Ipsum is not simply random text. It has roots in a piece of \n\n classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.
"""
offsets = [[10,20], [100,112]]

root = Tk()

text = Text(root)
text.insert(INSERT, example)
text.pack()
root.mainloop()

如何突出显示与 example[10:20]example[100:112] 对应的范围?

最佳答案

您可以定义一个标签,并将该标签应用于一系列字符。

您可以使用 1.0 + <offset>c 形式的索引这将计算一个新索引,该索引距索引 1.0 为 个字符。

例如:

text.tag_configure("highlight", background="yellow")
for start, end in offsets:
text.tag_add("highlight", "1.0 + %sc"%start, "1.0 + %sc"%end)

关于Python Tkinter 更改某些文本范围的文本背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34956423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com