简体   繁体   English

tkinter 文本小部件中的边距获取背景颜色

[英]margins in tkinter text widget acquire background color

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, eg 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) )在我的程序中的文本小部件中, lmargin1/lmargin2 用于根据其轮廓级别缩进文本(这些是与 tag_config 一起使用的选项,例如lmargin1(距离)用于文本块中第一行的左边距有这个标签。默认为 0(没有左边距)

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, eg:因此,如果缩进文本使用此标记,则边距空间中的背景也会发生变化,例如:

#!/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?有没有办法避免背景颜色污染页边距?

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.我解决这个问题的方法是将标签配置中的lmargincolor选项设置为Text小部件的背景颜色。 This will paint the margin added by lmargin1 / lmargin2 in that color (see the official manual ).这将以该颜色绘制由lmargin1 / lmargin2添加的边距(请参阅官方手册)。

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 .或者,您当然可以使用静态颜色,如#FFF

This worked like a charm for me, resulting in this look (with the amber-background text being the tag in question).这对我来说就像一个魅力,导致了这种外观(琥珀色背景文本是有问题的标签)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM