2014-02-10 231 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