[英]Changing color for different letters in python tkinter
我想为不同的字母使用不同的颜色。 例如a
字母将是yellow
和b
信将blue
在Text()
窗口小部件。
对于窗户。
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.