3

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)
0

1 Answer 1

5

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! very helpful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.