Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to colour a specific item in a Listbox widget?

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.

like image 939
Chris Allen Avatar asked Mar 18 '11 05:03

Chris Allen


People also ask

What is the default selection mode of a Listbox widget?

The default mode is "browse". These modes are similar in that only one item can be selected at a time; clicking on any item will deselect any other selection in the Listbox.

What is the use of Listbox widget?

The ListBox widget is used to display different types of items. These items must be of the same type of font and having the same font color. The items must also be of Text type. The user can select one or more items from the given list according to the requirement.

What is the use of Listbox widget give an example to add elements to Listbox using tkinter?

The Listbox widget is used to display the list items to the user. We can place only text items in the Listbox and all text items contain the same font and color. The user can choose one or more items from the list depending upon the configuration.


1 Answers

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()
like image 123
luc Avatar answered Nov 09 '22 03:11

luc