Alex Kross
Alex Kross

Reputation: 165

How to change the properties of selected text only in tkinter

This code changes the color of the text you enter

from tkinter import*

from tkinter.colorchooser import*

def getColor():
    color = askcolor()
    text['fg'] = color[1]

root=Tk()
text=Text(root)
text.pack()

king=Menu(root)
root.config(menu=king)

view= Menu(king,tearoff = 0)

view2=Menu(view,tearoff=0)
view2.add_command(label='Color',command=getColor)

view.add_cascade(label='Text',menu=view2)

king.add_cascade(label="View",menu=view)

But I need to change the selected text. For example, we entered the text "Hello my name's Alex", change the color of the whole text to red, then select the word "Alex" and change only its color. perhaps here it is necessary to apply, but I don't know how text.bind ('<B1-Motion>') text.tag_add(SEL_FIRST,SEL_LATS)

Help me please

Upvotes: 0

Views: 1368

Answers (1)

fhdrsdg
fhdrsdg

Reputation: 10532

You don't need to bind B1-Motion to make this work, because you can get the currently selected text easily. Every time a color is chosen you can check if there is a selection. When there isn't, you can simply change the foreground attribute of the Text widget. If there is, you need to create a tag on the current selection and change the foreground of the tag. However, you need to make a new tag name every time you do this to keep from changing the color of the previous selection, you can use a simple counter for this which you add to the tag name.

In code, it can look like this:

from tkinter import *
from tkinter.colorchooser import *

def getColor():
    global count
    color = askcolor()
    if text.tag_ranges('sel'):
        text.tag_add('colortag_' + str(count), SEL_FIRST,SEL_LAST)
        text.tag_configure('colortag_' + str(count), foreground=color[1])
        count += 1
    else:
        # Do this if you want to overwrite all selection colors when you change color without selection
        # for tag in text.tag_names():
        #     text.tag_delete(tag)
        text.config(foreground=color[1])

root=Tk()
text=Text(root)
text.pack()

count = 0

king=Menu(root)
root.config(menu=king)

view= Menu(king, tearoff=0)
view2=Menu(view, tearoff=0)
view2.add_command(label='Color',command=getColor)

view.add_cascade(label='Text', menu=view2)
king.add_cascade(label='View', menu=view)

root.mainloop()

Upvotes: 1

Related Questions