如何更改 tkinter 文本小部件中某些单词的颜色? [英] How to change the color of certain words in the tkinter text widget?
问题描述
我有一个程序,我希望它像 Python shell 一样,并在键入时更改某些单词的颜色.有什么帮助吗?
I have a program that I want to be like the Python shell and change color of certain words when they are typed. Any help?
推荐答案
主要思想是将标签应用到您想要自定义的文本部分.您可以使用方法 tag_configure
<创建标签/a>,具有特定的样式,然后您只需要使用方法 tag_add
.您还可以使用 tag_remove
方法删除标签.
The main idea is to apply tags to the parts of text you want to customise. You can create your tags using the method tag_configure
, with a specific style, and then you just need to apply this tag to the part of text you want to change using the method tag_add
.
You can also remove the tags using the method tag_remove
.
以下是使用 tag_configure
、tag_add
和 tag_remove
方法的示例.
The following is an example that uses tag_configure
, tag_add
and tag_remove
methods.
#!/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
是什么,请查看 这篇文章 或这篇 参考.
If you don't know what sel.first
and sel.last
are, check out this post or this reference.
这篇关于如何更改 tkinter 文本小部件中某些单词的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!