如何在tkinter中提供两种字体背景颜色?

时间:2016-11-09 13:20:55

标签: python tkinter

我的文本框包含以下数据

head
this is the heading

paragraph1
this is the paragraph1

paragraph2
this is the paragraph2

-----END-------

head
this is the heading

paragraph1
this is the paragragrph1

paragraph2
this is the paragragrph2

paragraph3
this is the paragragrph3

我正在尝试将红色添加为head的背景颜色和paragraph的绿色,所以我尝试了以下

line_number = 1
match_color = 0
for Z in (etc_data):
    if(re.match("head",Z)):
        str_len = len(Z)
        output_txtbox.tag_add("start", "%d.0"%(line_number), "%d.%s"%(line_number,str_len))
        output_txtbox.tag_config("start", background="red", foreground="white")
        match_color = 0
    if(re.match("paragraph",Z)):
        print "HI";
        str_len = len(Z)
        output_txtbox.tag_add("start", "%d.0"%(line_number), "%d.%s"%(line_number,str_len))     
        output_txtbox.tag_config("start", background="green", foreground="white")           
    line_number += 1
    match_color+=1

但问题是两者都显示red color。我不知道是什么问题。我该如何解决?

1 个答案:

答案 0 :(得分:2)

我认为这是因为您有两次相同的标记:start。你可以尝试:

line_number = 1
match_color = 0  
for Z in (etc_data):
    if(re.match("head",Z)):
        str_len = len(Z)
        output_txtbox.tag_add("tag_head", "%d.0"%(line_number), "%d.%s"%    (line_number,str_len))

        match_color = 0
    if(re.match("paragraph",Z)):
        print "HI";
        str_len = len(Z)
        output_txtbox.tag_add("tag_paragraph", "%d.0"%(line_number), "%d.%s"%    (line_number,str_len))     

    line_number += 1
    match_color+=1             

# Configuring tags
output_txtbox.tag_config("tag_head", background="red",     foreground="white")
output_txtbox.tag_config("tag_paragraph", background="green",     foreground="white")