Home > other >  How can I let the tkinter's text component show colorful words use '\033'?
How can I let the tkinter's text component show colorful words use '\033'?

Time:09-13

I have making enter image description here

CodePudding user response:

As for newbie. Just 15 lines try this.

import tkinter as tk

def onclick():
   pass

root = tk.Tk()
text = tk.Text(root)
text.insert(tk.INSERT, "It shows a tofu and [1mabc But I want get a red abc. How can I get it")
text.pack()

text.tag_add("here", "1.0", "1.4")
text.tag_add("start", "1.47", "1.51")
#text.tag_config("start", background="yellow", foreground="red")
text.tag_config("start", foreground="red")
root.mainloop()

If you want background and foreground. Comment in line13 and comment out line 14.

Output:

enter image description here

CodePudding user response:

for intermediate levels. If you want, select any word or multiple words and highlight and then clear it. I added two buttons.

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="Highlight",
                      command=self.highlight_text)
        
        self.bold_btn.pack(side="left")

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

        self.text = tk.Text(self)
        self.text.insert("end", "It shows a tofu and [1mabc. But I want get a red abc. How can I get i")
        self.text.focus()
        self.text.pack(fill="both", expand=True)
        
        self.text.tag_configure("start", foreground="red")
        #self.text.tag_configure("start", background="black", foreground="red")

    def highlight_text(self):   
        try:
            self.text.tag_add("start", "sel.first", "sel.last")     
        except tk.TclError:
            pass


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


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


if __name__ == "__main__":
    demo()

Output:

enter image description here

Btw, if you want background and foreground. Comment out line 29 and comment in line 30.

  • Related