简体   繁体   中英

Changing colour of item in Tkinter listbox

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM