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

Python 如何更改tkinter文本小部件中某些单词的颜色?,python,python-3.x,tkinter,Python,Python 3.x,Tkinter,我有一个程序,我想像Python外壳一样,在键入某些单词时改变它们的颜色。有什么帮助吗?看看这个例子: 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) #

我有一个程序,我想像Python外壳一样,在键入某些单词时改变它们的颜色。有什么帮助吗?

看看这个例子:

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()
我做了一个聊天客户端。 我使用一个定制的非常易于使用的
Text
小部件突出显示了对话的某些部分,该小部件允许您使用正则表达式应用标记。它基于以下帖子:

这里有一个使用示例:

# "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")
其主要思想是将标记应用于要自定义的文本部分。您可以使用该方法创建具有特定样式的标记,然后只需将该标记应用于要使用该方法更改的文本部分。 也可以使用该方法删除标记

下面是使用
tag\u configure
tag\u add
tag\u 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()

如果您不知道什么是
sel.first
sel.last
,请检查或参考。

我可以使用自定义tkinter小部件文本更改正则表达式每个匹配项的文本颜色,以获得与“text\u changed”类似的事件:

import tkinter as tk

class CustomText(tk.Text):

def __init__(self, *args, **kwargs):
    """A text widget that report on internal widget commands"""
    tk.Text.__init__(self, *args, **kwargs)

    # create a proxy for the underlying widget
    self._orig = self._w + "_orig"
    self.tk.call("rename", self._w, self._orig)
    self.tk.createcommand(self._w, self._proxy)

def _proxy(self, command, *args):
    cmd = (self._orig, command) + args
    result = self.tk.call(cmd)
    if command in ("insert", "delete", "replace"):
        self.event_generate("<<TextModified>>")
    return result
将tkinter作为tk导入
类CustomText(tk.Text):
定义初始化(self,*args,**kwargs):
“”“报告内部小部件命令的文本小部件”“”
tk.Text.\uuuu init\uuuuu(self,*args,**kwargs)
#为基础小部件创建代理
self._orig=self._w+“_orig”
self.tk.call(“重命名”,self.\w,self.\u orig)
self.tk.createcommand(self.\u w,self.\u代理)
def_代理(self、command、*args):
cmd=(self.\u orig,command)+args
结果=self.tk.call(cmd)
如果命令位于(“插入”、“删除”、“替换”):
self.event_generate(“”)
返回结果
然后,像这样使用它:

scr = CustomText(w)
scr.tag_configure('red', foreground = 'red')
scr.tag_configure('purple', foreground = '#a820a1')
scr.bind('<<TextModified>>', self.__textchanged__)

def __textchanged__(self, evt):
    for tag in evt.widget.tag_names():
        evt.widget.tag_remove(tag, '1.0', 'end')
    lines = evt.widget.get('1.0', 'end-1c').split('\n')
    for i, line in enumerate(lines):
        self.__applytag__(i, line, 'red', 'while|if', evt,widget) # your tags here
        self.__applytag__(i, line, 'purple', 'True', evt.widget)  # with a regex

@staticmethod
def __applytag__ (line, text, tag, regex, widget):
    indexes = [(m.start(), m.end()) for m in re.finditer(regex, text)]
    for x in indexes:
        widget.tag_add(tag, f'{line+1}.{x[0]}', f'{line+1}.{x[1]}')
scr=CustomText(w)
scr.tag\u configure('red',前台='red')
scr.tag_configure('purple',前台='#a820a1')
scr.bind(“”,self.\uuuuu text已更改)
定义文本更改(自我,evt):
对于evt.widget.tag_names()中的标记:
evt.widget.tag_remove(tag'1.0','end')
lines=evt.widget.get('1.0','end-1c').split('\n')
对于i,枚举中的行(行):
self.uu applytag_uu(i,line,'red',while | if',evt,widget)#您的标签在这里
self.uu applytag_uu(i,line,'purple','True',evt.widget)#带有正则表达式
@静力学方法
def _uapplytag _;(行、文本、标记、正则表达式、小部件):
索引=[(m.start(),m.end())表示re.finditer(regex,text)中的m)
对于索引中的x:
tag_add(tag,f'{line+1}.{x[0]}',f'{line+1}.{x[1]})

对不起,朋友!您可以使用tag_config更改文本小部件的字体和其他内容,但我尝试的颜色失败了

text.tag_配置(“警告”,fg=“黄色”)
_tkinter.tclError:位图“黄色”未定义p

标记添加(标记名,startindex[,endindex]…)此方法标记startindex定义的位置,或者由位置startindex和endindex分隔的范围。问题是1.8和1.13是文本所在的位置。我希望它在出现文本时改变颜色一点也没有帮助-我似乎无法为文本指定字体颜色。仅凭这些信息,我们帮不了你。可能会问一个新问题,并提供一个示例,我们可以运行该示例并检查您所说的是否属实。该示例仅在选择文本并单击
Bold
按钮后有效,并且不会在用户键入特定单词时自动突出显示。但是OP需要自动高亮显示。是否可以使用tkinter?一个问题
AttributeError:“Text”对象没有属性“highlight\u pattern”