如何在 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” 使用某种特定的颜色。

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP