我使用的是python/tkinter中的文本小部件.

我想对标记使用向左和向右选项,以便紧接在已标记文本之前或之后插入的文本位于相同的标记范围内.

在下面的代码中,我不明白为什么插入的文本没有显示为红色.

import tkinter as tk

main = tk.Tk()
tt = tk.Text(main, width=50, height=5, bg='lightgray')
tt.pack()

# some text
tt.insert('1.0', 'STRANGE!')

# inserting marks in text
tt.mark_set('redLeft', '1.2')
tt.mark_gravity('redLeft', 'left')
tt.mark_set('redRight', '1.6')
tt.mark_gravity('redRight', 'right')

# a tag for red text
tt.tag_add('red', 'redLeft', 'redRight')
tt.tag_configure('red', foreground='red')

# insertions after, in and before red text
tt.insert('1.6', 'should be red ?')
tt.insert('1.4', 'is red')
tt.insert('1.2', 'should be red ?')

main.mainloop()

谢谢你的帮助.

推荐答案

我不明白为什么插入的文本不显示为红色.

这就是文本小部件的工作方式.标记的重力不会影响插入文本时应用的标签.重力仅定义在标记处插入文本时标记发生的情况.

canonical documentation on marks人开始:

"The gravity for a mark specifies what happens to the mark when text is inserted at the point of the mark. If a mark has left gravity, then the mark is treated as if it were attached to the character on its left, so the mark will remain to the left of any text inserted at the mark position. If the mark has right gravity, new text inserted at the mark position will appear to the left of the mark (so that the mark remains rightmost)."

插入文本时,如果标签位于插入点左侧和右侧的字符both上,则文本将仅继承标签.

canonical documentation on the insert method人开始:

"If there is a single chars argument and no tagList, then the new text will receive any tags that are present on both the character before and the character after the insertion point; if a tag is present on only one of these characters then it will not be applied to the new text."

Python相关问答推荐

剧作家Python没有得到回应

在Pandas 日历中插入一行

使用LineConnection动画1D数据

Pydantic 2.7.0模型接受字符串日期时间或无

对某些列的总数进行民意调查,但不单独列出每列

Pandas 都是(),但有一个门槛

如何在虚拟Python环境中运行Python程序?

如何在python xsModel库中定义一个可选[December]字段,以产生受约束的SON模式

如何过滤包含2个指定子字符串的收件箱列名?

为什么以这种方式调用pd.ExcelWriter会创建无效的文件格式或扩展名?

如何从pandas的rame类继承并使用filepath实例化

如何使用scipy的curve_fit与约束,其中拟合的曲线总是在观测值之下?

在单个对象中解析多个Python数据帧

在嵌套span下的span中擦除信息

如何在Python中使用另一个数据框更改列值(列表)

Pandas:填充行并删除重复项,但保留不同的值

为用户输入的整数查找根/幂整数对的Python练习

如何在信号的FFT中获得正确的频率幅值

FileNotFoundError:[WinError 2]系统找不到指定的文件:在os.listdir中查找扩展名

我怎样才能让深度测试在OpenGL中使用Python和PyGame呢?