Tkinter 标签的优先级

Priority of Tkinter tags

I know this is a duplicate, but the other question did not have a valid answer, and was kind of confusing

当您将标签添加到 tkinter 文本小部件时,第一个标签具有优先权。如果最近添加的标签获得优先权,我会更喜欢它。在我的最小可重现示例中:

import tkinter as tk

win = tk.Tk()

txt = tk.Text(win)
txt.grid(row=0, column=0)

txt.insert('1.1', 'Hello Very Worldy World!')

txt.tag_add('tagone', '1.2', '1.4')
txt.tag_config('tagone', foreground='yellow')

txt.tag_add('tagtwo', '1.7', '1.13')
txt.tag_config('tagtwo', foreground='purple')

txt.tag_add('tagone', '1.6', '1.14')
txt.tag_config('tagone', foreground='yellow')

tk.mainloop()

如果你 运行 它,你会看到紫色标签出现在前景中,而不是黄色标签。有什么方法可以根据时间顺序而不是现在使用的顺序来定义标签优先级吗?

标签优先级基于标签的创建时间,而不是标签的应用时间。

来自 effbot:

If you attach multiple tags to a range of text, style options from the most recently created tag override options from earlier tags. In the following example, the resulting text is blue on a yellow background.

text.tag_config("n", background="yellow", foreground="red")
text.tag_config("a", foreground="blue")
text.insert(contents, ("n", "a"))

Note that it doesn’t matter in which order you attach tags to a range; it’s the tag creation order that counts.

You can change the tag priority using the tag_raise and tag_lower. If you add a text.tag_lower("a") to the above example, the text becomes red.

因为您在 tagtwo 之前创建了 tagone,所以 tagtwo 获得优先权。您可以通过给第三个范围一个新名称 (tagthree)、在创建 tagone 之前创建 tagtwo 或使用 txt.tag_lower('tagtwo')/txt.tag_raise('tagone') 来获得预期的行为.