You can apply a tag to a range of characters in a text widget. Each tag can be configured with a variety of styles and a custom font. Some styles can be applied directly to the tag, some need to be applied to a font that is associated with the tag. Italics is one such style that must be applied to a font.
import tkinter as tk
from tkinter.font import Font
root = tk.Tk()
normal_font = Font(family="helvetica", size=20)
italic_font = Font(family="helvetica", size=20, slant="italic")
text = tk.Text(root, wrap="none", width=40, height=10, font=normal_font)
text.pack(fill="both", expand=True)
text.tag_configure("italics", font=italic_font)
text.insert("end", "This is ", "", "my", "italics", " text widget")
root.mainloop()
注:insert
这种方法通常用于在某一时间插入一个插图,但实际上以text、tag/em>、、>>>>>>>>>、......(最后标签可以省略)。
In the above example, we insert the whole string using a single call to insert
, but notice how we apply a null tag to some parts, and the tag "italics" to the word "my". That one call to insert
does exactly the same thing as these three lines, but in a more concise format:
text.insert("end", "This is ")
text.insert("end", "my", "italics")
text.insert("end", " text widget")
这样做的另一个方式是一劳永逸地插入整个插图,然后在一份单独声明中添加标记:
text.insert("end", "This is my text widget")
text.tag_add("italics", "1.8", "1.9")