I have been working trying to make a simple text editor, and have been experimenting with tags. I have been able to create justifying using tags. Now I\'m adding a bold opti
Tag attributes belong to the tag, not to the text. So, when you highlight something then apply attributes to the "sel"
tag, it only affects text that has the "sel"
tag. When you remove the tag (by unhighlighting), the attributes revert to the default (or to any other tags that might be present).
To make text bold, you must create a tag that has the bold attribute and assign that tag to the text. As long as the text has that tag, it will have the attributes of that tag.
You would only need tag_add()
inside of your function:
import Tkinter as tk
def make_bold():
aText.tag_add("bt", "sel.first", "sel.last")
lord = tk.Tk()
aText = tk.Text(lord, font=("Georgia", "12"))
aText.grid()
aButton = tk.Button(lord, text="bold", command=make_bold)
aButton.grid()
aText.tag_config("bt", font=("Georgia", "12", "bold"))
lord.mainloop()
I just happened across a rather educational example by none other than Bryan Oakley,
on a completely unrelated search!
Here is a quick example of the more dynamic alternative:
import Tkinter as tk
import tkFont
def make_bold():
current_tags = aText.tag_names("sel.first")
if "bt" in current_tags:
aText.tag_remove("bt", "sel.first", "sel.last")
else:
aText.tag_add("bt", "sel.first", "sel.last")
lord = tk.Tk()
aText = tk.Text(lord, font=("Georgia", "12"))
aText.grid()
aButton = tk.Button(lord, text="bold", command=make_bold)
aButton.grid()
bold_font = tkFont.Font(aText, aText.cget("font"))
bold_font.configure(weight="bold")
aText.tag_configure("bt", font=bold_font)
lord.mainloop()