Question

In a text widget I have in my program, lmargin1/lmargin2 are used to indent text based on its outline level (those are options used with tag_config, e.g. lmargin1 (distance) The left margin to use for the first line in a block of text having this tag. Default is 0 (no left margin))

My problem is that I defined a highlight text tag, which changes the background. So if an indented text uses this tag, the background changes also in the margin spaces, e.g.:

#!/usr/bin/env python
from Tkinter import *

root = Tk()
configtext = Text(root, width=150)
configtext.pack()
configtext.tag_configure('n', lmargin1=45, lmargin2=45)
configtext.tag_configure('nh', lmargin1=45, lmargin2=45,  background="yellow", foreground="red")

con1="L'Italia è una Repubblica democratica, fondata sul lavoro. La sovranità appartiene al popolo" 
con2=" che la esercita nelle forme e nei limiti della Costituzione. La Repubblica riconosce e garantisce i diritti inviolabili dell'uomo"
con3=" sia come singolo sia nelle formazioni sociali ove si svolge la sua personalità, e richiede l'adempimento dei doveri inderogabili di solidarietà politica, economica e sociale.\n\n"
configtext.insert(INSERT,con1+con2+con3)
configtext.insert(INSERT,con1,'n')
configtext.insert(INSERT,con2,'nh')
configtext.insert(INSERT,con3,'n')
mainloop()

there is a way to avoid polluting the margins with the background color?

Was it helpful?

Solution

This is quite an old question, but considering I stumbled upon it today looking for an answer, others with the same issue might appreciate this being updated.

The way I solved this was by setting the lmargincolor option in the tag configuration to the background color of the Text widget. This will paint the margin added by lmargin1/lmargin2 in that color (see the official manual).

In my case, this looked like this:

text_widget.tag_configure(
    tagName="warning",
    background="#ff9800",
    lmargin1=margin1
    lmargin2=margin2,
    lmargincolor=text_widget.cget("background")
)

Alternatively, you could of course use a static color like #FFF.

This worked like a charm for me, resulting in this look (with the amber-background text being the tag in question).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top