如何在 tkinter 文字小工具中高亮顯示文字?


Tkinter 文字小工具用於建立接受多行使用者輸入的文字域。假設我們希望在文字小工具中高亮顯示某些文字。為了高亮顯示在文字小工具中寫入的特定文字,tkinter 提供了 tag_add(tag, i,j) 方法。它透過定義索引 ij 將標籤新增到特定文字。

示例

在此示例中,我們將建立一個視窗應用程式,其中包含一些文字和一個可觸發以高亮顯示文字的按鈕。

#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()

輸出

執行上述程式碼將顯示一個視窗,其中包含一個按鈕和一些文字。

現在,單擊“高亮顯示”按鈕以高亮顯示“你好?”文字。

更新於: 2021-4-16

5000+ 瀏覽

職業生涯啟動

透過完成課程獲得認證

開始
廣告