簡體   English   中英

在python tkinter中更改不同字母的顏色

[英]Changing color for different letters in python tkinter

我想為不同的字母使用不同的顏色。 例如a字母將是yellowb信將blueText()窗口小部件。

對於窗戶。

from tkinter import *

app = Tk()

txt = Text(app)
txt.pack()

app.mainloop()

我怎樣才能做到這一點?

您可以使用.tag_config(...)在某些tags上應用顏色,然后在Text小部件上綁定<KeyRelease>事件處理程序以使用.tag_add(...)在輸入上添加tag

下面是一個例子:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM