如何在 tkinter 文本小工具中高亮显示文本?
Tkinter 文本小工具用于创建接受多行用户输入的文本域。假设我们希望在文本小工具中高亮显示某些文本。为了高亮显示在文本小工具中写入的特定文本,tkinter 提供了 tag_add(tag, i,j) 方法。它通过定义索引 i 和 j 将标签添加到特定文本。
示例
在此示例中,我们将创建一个窗口应用程序,其中包含一些文本和一个可触发以高亮显示文本的按钮。
#Import tkinter library from tkinter import * #Create an instance of tkinter frame win= Tk() win.geometry("750x450") #Define a function to highlight the text def add_highlighter(): text.tag_add("start", "1.11","1.17") text.tag_config("start", background= "black", foreground= "white") #Create a Tex Field text= Text(win); text.insert(INSERT, "Hey there! Howdy?") text.pack() #Create a Button to highlight text Button(win, text= "Highlight", command= add_highlighter).pack() win.mainloop()
输出
运行上述代码将显示一个窗口,其中包含一个按钮和一些文本。
现在,单击“高亮显示”按钮以高亮显示“你好?”文本。
广告