Question

I am using tags in my Tkinter Text widget yet on certain lines the background colour is changed to a light grey/blue however when a user highlights these lines the colour is not noticeable between the text and whether it has been highlighted or not. Is there an option I can add to my tag configure method call to change the highlight colour? Currently it looks like:

self.text.tag_config("oddLine", background="#F3F6FA")

Here is a screenshot of how it looks before a user highlights the text: Before highlight

And after is hard to notice that the user has highlighted the middle line:

After Highlighting

How can I get the colour of what the user selects to be more consistent so that lines that have the background similar to the highlighting colour look similar.

Was it helpful?

Solution

Tags have a priority. What is happening is that your tag has a higher priority than the selection. If you lower the priority of your tag, or raise the priority of the sel tag, the selection will be more visible.

Try this:

self.text.tag_raise("sel")

OTHER TIPS

I am not aware of a way to specify an highlight colour for a Text tag.

I see two ways to solve your problem, the first is to give "sel" tag precedence over your oddLine tag, as pointed by Bryan. Text tags are ordered according their order of creation (last created above others). The default "sel" tag is created with the widget and thus is below any later added tag.

A second way would be to compute the intersection between your tag and "sel" to provide a custom style. Here is a snippet achieving this behavior.

import Tkinter as tk

t = tk.Text()
t.pack()
t.insert(tk.END, "Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
t.tag_config("foo", background="yellow", foreground="red")
t.tag_add("foo", "1.6", "1.11")
t.tag_add("foo", "1.28", "1.39")

t.tag_config("sel_intersection", background="orange")

def sel_manager(event):
    t = event.widget
    tag_remove_all (t, "sel_intersection")

    f = map(TextIndex, t.tag_ranges("foo"))
    s = map(TextIndex, t.tag_ranges("sel"))

    if (len(s) == 0):
        return
    for f_start, f_end in zip(f[::2],f[1::2]):
        t.tag_add("sel_intersection", max(s[0],f_start), min(s[1], f_end))

def tag_remove_all(widget, tag_name):
    ranges =  map(str, t.tag_ranges(tag_name))
    for s, e in zip(ranges[::2], ranges[1::2]):
        widget.tag_remove(tag_name, s, e)

class TextIndex:
    '''needed for proper index comparison, ie "1.5" < "1.10"
    '''
    def __init__(self, textindex):
        self._str = str(textindex)
        self._l , self._c = map(int, self._str.split('.'))
    def __cmp__(self, other):
        cmp_l = cmp(self._l, other._l)
        if cmp_l !=0:
            return cmp_l
        else:
            return cmp(self._c, other._c)
    def __str__(self):
        return self._str

t.bind("<<Selection>>", sel_manager)
t.mainloop()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top