2014-02-10 234 views
1

我正在寻找这个example用于填充具有背景颜色的文本小部件。不过,我希望背景颜色不仅出现在有文字的地方,而且还出现在整条线上。所以从这个例子我可以说:Tkinter用背景颜色填充整行

text.tag_add("here", "1.0", "1.80") 
text.tag_config("here", background="yellow", foreground="blue") 

这是因为一个标准的文本部件是80个字符宽。这也没有工作:

text.tag_add("here", "1.0", 1.END) 
text.tag_config("here", background="yellow", foreground="blue") 

这些都有同样的不良影响。我试图实现的效果与iTunes列表类似(请参阅图像),其中每行都以颜色交替显示。这是可以通过使用文本元素来实现吗?我知道他们是交替排列不同颜色的表格,但是我有简单的字符串,这些字符串因另一个因素而异,并且认为这是显示不同之处的好方法。

Example of iTunes list

回答

2

指定line_number + 1.0endindex

UPDATE

指定line_number.0+1lines作为endindex。 (见The Tkinter Text Widget documentation,尤其是表达式部分)

小例子:

try: 
    from tkinter import * 
except ImportError: 
    from Tkinter import * 

text = Text() 
text.pack() 
text.insert(END, '1st\n2nd\n3rd') 
# text.tag_add("here", "2.0", "3.0") # <---------------------- 
text.tag_add("here", "2.0", "2.0+1lines") # <---------------------- 
text.tag_config("here", background="yellow", foreground="blue") 
mainloop() 

enter image description here

+0

我没有想到要增加的行号,因为我认为它会也改变了背景该线的颜色。 – Dean

+1

@Dean,我发现比手动添加1更好的方法。我更新了答案。一探究竟。 – falsetru