Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...