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()输出结果
运行上面的代码将显示一个窗口,其中包含一个按钮和一个文本。
现在,单击“突出显示”按钮以突出显示文本“Howdy?”