基于文本Widg中的第一个字符标记整个单词

2024-04-19 23:09:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着在第一个字符的基础上标记并突出显示整个单词。在下面的示例中,我正在搜索hashtags“#”。我想标记并突出显示后面的字符,直到下一个空格。所以字符“#hashtag”都应该以蓝色突出显示。下面的代码查找hashtags并将其高亮显示为蓝色,但不显示后续字符。我假设问题是我在self.text_box.tag_add("hashtag{}".format(x), self.index, self.index + "wordend")中没有正确地使用"wordend",但是我不知道我做错了什么。你知道吗

据effbot.org网站你知道吗

“wordstart” and “wordend” moves the index to the beginning (end) of the current word. Words are sequences of letters, digits, and underline, or single non-space characters. http://effbot.org/tkinterbook/text.htm

欢迎指点。你知道吗

下面是一些复制问题的示例代码:

import tkinter as tk
import tkinter.scrolledtext as St

    class Main(tk.Tk):

    def __init__(self):

        tk.Tk.__init__(self)
        self.text = "random text\nrandom text\n#hashtag random text\n#hashtag"

        self.text_box = St.ScrolledText(self)
        self.text_box.pack()

        self.text_box.insert("1.0", self.text)

        self.index = self.text_box.search("#", "1.0", stopindex=tk.END)
        x = 0
        while self.index != "":
            self.text_box.tag_add("hashtag{}".format(x), self.index, self.index + "wordend")
            self.text_box.tag_configure("hashtag{}".format(x), foreground="blue")
            self.index += "+1c"
            self.index = self.text_box.search("#", self.index, stopindex=tk.END)
            x += 1

main=Main()
main.mainloop()

Tags: thetext标记selfboxformat示例index
2条回答

我把tag.add行改为

self.text_box.tag_add("hashtag{}".format(x), self.index, (self.index + "+1c") + " wordend").

但是我不知道为什么我需要在tag.add命令的结束索引中添加额外的字符?有人能解释一下吗?你知道吗

从规范的tcl/tk文档中:

A word consists of any number of adjacent characters that are letters, digits, or underscores, or a single character that is not one of these. If the display submodifier is given, this only examines non-elided characters, otherwise all characters (elided or not) are examined.

在您的例子中,“3.0”后面的字符是#,这是“不是其中之一”,因此单个字符被认为是一个单词,因此“wordend”修饰符在该单个字符之后停止。你知道吗

如果您希望一个hashtag加上它后面的单词被赋予标签,那么您的第二个索引应该是“行.char+1c wordend”(例如:“3.0+1c wordend”),这样您可以查找以哈希后面的第一个字符开始的单词结尾,而不是以哈希本身开始。你知道吗

相关问题 更多 >