Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set to bold the selected text using tags

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 option.

My problem is that I can't find many examples of using the "sel" tag, a tag used on current selection.

Whenever I use the SEL tag, the text is only bold as long as it is highlighted, when it becomes un-highlighted, it reverts back to its old skinny font.

This is a small portion of my code:

def Bold(self, body, Just, Line, selected font):
    bold font = tkFont.Font(family=selectedfont, weight="bold")
    selected font = boldfont
    body.tag_config("sel",font=selectedfont)
    body.tag_add("sel", 1.0,END)

When the Bold button is pressed, the previous function is called. Right now, I have the body.tag_add("sel", 1.0, END) set from 1.0 to END, because I don't know how to get the selected domain. I've tried <<Selection>>, but after experimenting for a long time, it hasn't helped me.

like image 263
reallycoolnerd Avatar asked Jan 17 '23 01:01

reallycoolnerd


2 Answers

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()
like image 152
Honest Abe Avatar answered Jan 28 '23 14:01

Honest Abe


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.

like image 30
Bryan Oakley Avatar answered Jan 28 '23 14:01

Bryan Oakley