📜  更改 tkinter 文本小部件中某些单词的颜色

📅  最后修改于: 2022-05-13 01:55:47.212000             🧑  作者: Mango

更改 tkinter 文本小部件中某些单词的颜色

Python有多种用于图形用户界面 (GUI) 开发的选项。选项之一是 Tkinter。 Tkinter 和Python共同为 GUI 开发提供了一种更快的方式。 Tk GUI 工具包提供了一个面向对象的界面。

为了使用 Tkinter 创建 GUI 应用程序,我们必须遵循几个步骤 -

  • 导入 Tkinter 模块。
  • 创建主窗口。
  • 根据要求将各种小部件添加到 GUI 应用程序。
  • 用户为执行特定操作而触发的每个触发器的主事件循环。

文本小部件具有用于编辑多行文本和格式化该文本示例字体、文本颜色、背景颜色的显示设置的高级选项。我们还可以使用标签和标记来定位和编辑数据部分。我们还可以在文本中使用图像并插入边框。一切都可以根据要求进行格式化。

示例 1:在第一个示例中,我们将通过指定索引并突出显示选定的文本来为一段文本添加一个标签。在这里,我们使用 tag_add 和 tag_config。

Python3
# import all functions from the tkinter
from tkinter import *
  
# Create a GUI window  
root = Tk()
  
# Create a text area box   
# for filling or typing the information.
text = Text(root)
  
# insert given string in text area
text.insert(INSERT, "Hello, everyone!\n")
  
text.insert(END, "This is 2020.\n")
  
text.insert(END, "Pandemic has resulted 
             in economic slowdown worldwide")
  
text.pack(expand=1, fill=BOTH)
  
# add tag using indices for the
# part of text to be highlighted
text.tag_add("start", "2.8", "1.13")
  
#configuring a tag called start
text.tag_config("start", background="black",
                 foreground="red")
  
# start the GUI
root.mainloop()


Python3
# import all functions from the tkinter   
import tkinter as tk
from tkinter.font import Font
  
# create a Pad class
class Pad(tk.Frame):
  
    # constructor to add buttons and text to the window
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
  
        self.toolbar = tk.Frame(self, bg="#eee")
        self.toolbar.pack(side="top", fill="x")
          
        # this will add Highlight button in the window
        self.bold_btn = tk.Button(self.toolbar, text="Highlight",
                                  command=self.highlight_text)
        self.bold_btn.pack(side="left")
  
        # this will add Clear button in the window
        self.clear_btn = tk.Button(self.toolbar, text="Clear",
                                   command=self.clear)
        self.clear_btn.pack(side="left")
  
        # adding the text 
        self.text = tk.Text(self)
        self.text.insert("end", "Pandemic has resulted in economic slowdown worldwide")
        self.text.focus()
        self.text.pack(fill="both", expand=True)
          
        #configuring a tag called start
        self.text.tag_configure("start", background="black", foreground="red")
  
    # method to highlight the selected text
    def highlight_text(self):
          
        # if no text is selected then tk.TclError exception occurs
        try:
            self.text.tag_add("start", "sel.first", "sel.last")        
        except tk.TclError:
            pass
  
    # method to clear all contents from text widget.
    def clear(self):
        self.text.tag_remove("start",  "1.0", 'end')
  
# function
def demo():
  
    # Create a GUI window 
    root = tk.Tk()
  
    # place Pad object in the root window
    Pad(root).pack(expand=1, fill="both")
  
    # start the GUI
    root.mainloop()
  
# Driver code
if __name__ == "__main__":
  
    # function calling
    demo()


输出 :

示例 2:在此示例中,用户可以通过选择要突出显示的文本来根据自己的意愿突出显示文本。在这里,我们使用 tag_configure 和 tag_add。

Python3

# import all functions from the tkinter   
import tkinter as tk
from tkinter.font import Font
  
# create a Pad class
class Pad(tk.Frame):
  
    # constructor to add buttons and text to the window
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
  
        self.toolbar = tk.Frame(self, bg="#eee")
        self.toolbar.pack(side="top", fill="x")
          
        # this will add Highlight button in the window
        self.bold_btn = tk.Button(self.toolbar, text="Highlight",
                                  command=self.highlight_text)
        self.bold_btn.pack(side="left")
  
        # this will add Clear button in the window
        self.clear_btn = tk.Button(self.toolbar, text="Clear",
                                   command=self.clear)
        self.clear_btn.pack(side="left")
  
        # adding the text 
        self.text = tk.Text(self)
        self.text.insert("end", "Pandemic has resulted in economic slowdown worldwide")
        self.text.focus()
        self.text.pack(fill="both", expand=True)
          
        #configuring a tag called start
        self.text.tag_configure("start", background="black", foreground="red")
  
    # method to highlight the selected text
    def highlight_text(self):
          
        # if no text is selected then tk.TclError exception occurs
        try:
            self.text.tag_add("start", "sel.first", "sel.last")        
        except tk.TclError:
            pass
  
    # method to clear all contents from text widget.
    def clear(self):
        self.text.tag_remove("start",  "1.0", 'end')
  
# function
def demo():
  
    # Create a GUI window 
    root = tk.Tk()
  
    # place Pad object in the root window
    Pad(root).pack(expand=1, fill="both")
  
    # start the GUI
    root.mainloop()
  
# Driver code
if __name__ == "__main__":
  
    # function calling
    demo()

输出 :

在选择文本并点击突出显示按钮之前:

选择文本并点击突出显示按钮后: