如何在 Tkinter 文字小元件中更改特定單詞的顏色?


Tkinter 文字小元件用於建立和顯示多行文字輸入。它提供了一些函式和方法,通常用於配置文字小元件。

假設我們要更改文字小元件中特定單詞的顏色,那麼我們可以使用 tag_add(tag name, range) 方法,該方法會選中我們要格式化的單詞。選中單詞後,我們可以使用 tag_config(properties) 方法更改其顏色、背景顏色和其他屬性。

示例

在此示例中,我們將配置文字小元件中選中單詞的顏色。

#Import required libraries
from tkinter import *

#Create an instance of tkinter window
win =Tk()

#Define the geometry of the window
win.geometry("600x250")

#Create a text widget
text= Text(win)
text.insert(INSERT, "Hello World!\n")
text.insert(END, "This is a New Line")

text.pack(fill=BOTH)

#Configure the text widget with certain color
text.tag_config("start", foreground="red")
text.tag_add("start", "1.6", "1.12")

win.mainloop()

輸出

執行以上程式碼將顯示一個帶有以下文字的視窗:“Hello World”,其中 “World” 使用某種特定的顏色。

更新時間:2021 年 3 月 26 日

11K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.