2

In reference to Is it possible to colour a specific item in a Listbox widget? Is it possible to change the bg colour based on the data being held in the list.

For example:

In the list names there are several values, some positive, others negative. I want to change their background colour based on if they are positive or negative.

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

diffbox.insert(END, names)
Community
  • 1
  • 1
Tom Lowbridge
  • 879
  • 3
  • 9
  • 17

1 Answers1

3

index parameter of itemconfig() can be "end", you should take advantage of it. First insert the item to the end, then change its background.

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()
Lafexlos
  • 7,618
  • 5
  • 38
  • 53