15

I'm referring to a specific element in the Listbox widget.

Colouring the background is most desired but any form of colouring for a specific cell would be fantastic.

nbro
  • 15,395
  • 32
  • 113
  • 196
Chris Allen
  • 653
  • 4
  • 9
  • 17

1 Answers1

46

According to the effbot.org documentation regarding the Listbox widget you cannot change the color of spefic items:

The listbox can only contain text items, and all items must have the same font and color

But actually you can change both the font and background colors of specific items, by using the itemconfig method of your Listbox object. See the following example:

import tkinter as tk


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

    # inserting some items
    listbox.insert("end", "A list item")

    for item in ["one", "two", "three", "four"]:
        listbox.insert("end", item)

    # this changes the background colour of the 2nd item
    listbox.itemconfig(1, {'bg':'red'})

    # this changes the font color of the 4th item
    listbox.itemconfig(3, {'fg': 'blue'})

    # another way to pass the colour
    listbox.itemconfig(2, bg='green')
    listbox.itemconfig(0, foreground="purple")


if __name__ == "__main__":
    root = tk.Tk()
    demo(root)
    root.mainloop()
nbro
  • 15,395
  • 32
  • 113
  • 196
luc
  • 41,928
  • 25
  • 127
  • 172
  • ahhh... okay, thanks. I'm new to python and I was trying to use the .configure(bg="Green") – Chris Allen Mar 18 '11 at 08:28
  • 2
    This [documentation](https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/listbox.html) is a little clearer about what `itemconfig()` can do. – martineau Jan 08 '21 at 14:47
  • And for those trying to get the last inserted item like `listbox.itemconfig(-1, {'bg' : 'red'}`, use tk.END instead: `listbox.itemconfig(tk.END, {'bg' : 'red'}` – Sludge Aug 25 '22 at 15:54