【问题标题】:how do i change the color of a specific word in a text widget in python [duplicate]我如何在python的文本小部件中更改特定单词的颜色[重复]
【发布时间】:2019-12-07 14:32:04
【问题描述】:

所以我制作了一种 python 文本编辑器,我希望脚本扫描文本以查找特定单词,然后更改单词的颜色(如在 pycharm 中) 像这样:

txt.get() = word
if word == "print":
(change color of text)

(我知道关于这个有很多类似的问题,但我找不到任何对我有帮助的东西)

【问题讨论】:

  • 你说你见过类似的问题,但它们没有帮助。你能展示你的尝试吗?
  • 我的意思是他们的问题的解决方案在我的版本中没有用

标签: python tkinter


【解决方案1】:

为您创建了一些方法来实现这一点。 我建议阅读 Tk 文档(Text、Text.search()、Tags、Indexes)!

Tk 为您提供 text.search 方法,因此您无需实现自己的方法。 Tk Text 小部件为您提供标签,您可以创建和修改标签。

工作流程:
1. 使用 text.search() 方法搜索模式 这将返回起始位置的索引
2. 使用 text.tag_config()
创建一个标签 3. 用 text.tag_add() 添加创建的标签

from tkinter import Tk, Entry, Button, Text, IntVar
from tkinter import font

class Text_tag_example():
    def __init__(self, master):
        self.master = master  
        self.my_font = font.Font(family="Helvetica",size=18)
        self.startindex = "1.0"     #needed for search method, index ("line, column")
        self.endindex = "end"       #needed for search method, index (end of index)
        self.init_widgets()

    def init_widgets(self):

        self.txt_widget = Text(self.master, font=self.my_font, 
                            height=10, width=40)
        self.txt_widget.grid(row=0, columnspan=2)
        self.ent_string = Entry(self.master, font=self.my_font)
        self.ent_string.grid(row=1, column=0)
        self.but_search = Button(self.master, text="Search", font=self.my_font,
                            command=self.search_word)
        self.but_search.grid(row=1, column=1)

    def search_word(self):
        word = self.ent_string.get()    #get string from entry 
        countVar = IntVar()             # contain the number of chars that matched
        searched_position = self.txt_widget.search(pattern=word, index=self.startindex, 
                                                stopindex=self.endindex, count=countVar)
        self.txt_widget.tag_config("a", foreground="blue", underline=1)
        endindex = "{}+{}c".format(searched_position, countVar.get())   #add index+length of word/pattern
        self.txt_widget.tag_add("a", searched_position, endindex)

if __name__ == "__main__":
    root = Tk()
    app = Text_tag_example(root)
    root.mainloop()

用法:
- 输入文本小部件“你好,再见”
- 输入条目小部件“hi”
-按搜索按钮
-“hi”应该是蓝色的并带有下划线

您的下一个问题可能是“如何在文本中标记所有相同的单词?”
再次阅读文档,否则您将无法理解!

【讨论】:

    猜你喜欢
    • 2013-06-20
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    • 2019-03-26
    相关资源
    最近更新 更多