更改Tkinter列表框

时间:2016-04-28 12:06:48

标签: python tkinter listbox

参考Is it possible to colour a specific item in a Listbox widget?是否可以根据列表中保存的数据更改 bg颜色

例如:

在列表名称中有几个值,一些是正值,另一些是负值。我想根据它们是正面还是负面来改变它们的背景颜色。

if names > 0 :
    diffbox.itemconfig(bg='red')
if names < 0 :
    diffbox.itemconfig(bg='green')

diffbox.insert(END, names)

1 个答案:

答案 0 :(得分:1)

itemconfig()

index 参数可以是"end",您应该利用它。首先将项目插入end,然后更改其背景。

import Tkinter as tk

def demo(master):
    listbox = tk.Listbox(master)
    listbox.pack(expand=1, fill="both")

    # inserting some items
    for names in [0,1,-2,3,4,-5,6]:
        listbox.insert("end", names)
        listbox.itemconfig("end", bg = "red" if names < 0 else "green")

        #instead of one-liner if-else, you can use common one of course
        #if item < 0:
        #     listbox.itemconfig("end", bg = "red")
        #else:
        #     listbox.itemconfig("end", bg = "green")

if __name__ == "__main__":
    root = tk.Tk()
    demo(root)
    root.mainloop()