简体   繁体   中英

Changing color for different letters in python tkinter

I want to use different colors for different letters. For example a letter will be yellow and b letter will be blue in Text() widget.

For windows.

from tkinter import *

app = Tk()

txt = Text(app)
txt.pack()

app.mainloop()

How can I accomplish this?

You can use .tag_config(...) to apply colors on certain tags and then bind a <KeyRelease> event handler on Text widget to add tag on input using .tag_add(...) .

Below is an example:

import tkinter as tk

# colors for certain characters    
colormap = {'b':'blue', 'c':'cyan', 'g':'green', 'm':'magenta', 'o':'orange', 'p':'pink', 'r':'red', 'y':'yellow'}

def on_key(event):
    if event.char in colormap:
        # attach a tag (the character itself) if the character is in the colormap
        event.widget.tag_add(event.char, 'insert-1c')

root = tk.Tk()

text = tk.Text(root)
text.pack()
text.bind('<KeyRelease>', on_key) # on_key() will be executed when a key is pressed inside Text widget
# setup colors for certain characters using tag_config(...)
for c in colormap:
    text.tag_config(c, foreground=colormap[c])

root.mainloop()
import tkinter as tk


class Application(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.title("Colorful text")
        self.geometry("256x64")
        self.resizable(width=False, height=False)

        self.text = tk.Text(self)
        self.text.pack()
        self.text.insert("end", "First Line\nSecond Line")

        self.apply_color()

    def apply_color(self):
        from itertools import cycle

        colors = ["Red", "Green", "Blue"]
        color_iterator = cycle(colors)

        # Get the string from the tk.Text widget.
        text_str = self.text.get("1.0", "end-1c")

        lines = text_str.splitlines(True)

        for line_index, line in enumerate(lines, start=1):
            for char_index, char in enumerate(line):
                if char.isspace():
                    # Ignore whitespace
                    continue
                color = next(color_iterator)
                self.text.tag_add(color, f"{line_index}.{char_index}")
        for color in colors:
            self.text.tag_config(color, foreground=color)


def main():

    application = Application()
    application.mainloop()

    return 0

if __name__ == "__main__":
    import sys
    sys.exit(main())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM