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

Arc*_*ran 18 python tkinter python-3.x

我有一个程序,我希望像python shell一样,并在键入任何帮助时更改某些单词的颜色?

nbr*_*bro 23

主要思想是将标记应用于要自定义的文本部分.您可以使用tag_configure具有特定样式的方法创建标记,然后只需将此标记应用于要使用该方法更改的文本部分tag_add.您也可以使用该方法删除标记tag_remove.

以下是使用一个例子tag_configure,tag_addtag_remove方法.

#!/usr/bin/env python3

import tkinter as tk
from tkinter.font import Font

class Pad(tk.Frame):

    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")

        self.bold_btn = tk.Button(self.toolbar, text="Bold", command=self.make_bold)
        self.bold_btn.pack(side="left")

        self.clear_btn = tk.Button(self.toolbar, text="Clear", command=self.clear)
        self.clear_btn.pack(side="left")

        # Creates a bold font
        self.bold_font = Font(family="Helvetica", size=14, weight="bold")

        self.text = tk.Text(self)
        self.text.insert("end", "Select part of text and then click 'Bold'...")
        self.text.focus()
        self.text.pack(fill="both", expand=True)

        # configuring a tag called BOLD
        self.text.tag_configure("BOLD", font=self.bold_font)

    def make_bold(self):
        # tk.TclError exception is raised if not text is selected
        try:
            self.text.tag_add("BOLD", "sel.first", "sel.last")        
        except tk.TclError:
            pass

    def clear(self):
        self.text.tag_remove("BOLD",  "1.0", 'end')


def demo():
    root = tk.Tk()
    Pad(root).pack(expand=1, fill="both")
    root.mainloop()


if __name__ == "__main__":
    demo()
Run Code Online (Sandbox Code Playgroud)

如果你不知道什么是sel.firstsel.last是,看看这个职位参考.


Ade*_*taş 9

看看这个例子:

from tkinter import *

root = Tk()

text = Text(root)
text.insert(INSERT, "Hello, world!\n")
text.insert(END, "This is a phrase.\n")
text.insert(END, "Bye bye...")
text.pack(expand=1, fill=BOTH)

# adding a tag to a part of text specifying the indices
text.tag_add("start", "1.8", "1.13")
text.tag_config("start", background="black", foreground="yellow")

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

  • tag_add(tagname,startindex [,endindex] ...)此方法标记startindex定义的位置,或者由positionindex和endindex位置分隔的范围. (3认同)

Rnh*_*joj 9

我做了一个聊天客户端.我使用自定义的易于使用的Text小部件突出显示了对话的某些部分,该小部件允许您使用正则表达式应用标记.它基于以下帖子:如何突出显示tkinter文本小部件中的文本.

这里有一个使用示例:

# "text" is a Tkinter Text

# configuring a tag with a certain style (font color)
text.tag_configure("red", foreground="red")

# apply the tag "red" 
text.highlight_pattern("word", "red")
Run Code Online (Sandbox Code Playgroud)