是否可以为Listbox小部件中的特定项目着色?

Chr*_*len 7 python user-interface listbox tkinter colors

我指的是Listbox小部件中的特定元素.

最需要着色背景,但特定细胞的任何形式的着色都会很棒.

luc*_*luc 22

根据effbot.org有关Listbox小部件的文档,您无法更改特定项目的颜色:

列表框只能包含文本项,并且所有项必须具有相同的字体和颜色

但实际上,您可以使用对象的itemconfig方法更改特定项目的字体和背景颜色Listbox.请参阅以下示例:

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()
Run Code Online (Sandbox Code Playgroud)

  • 这个[文档](https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/listbox.html)更清楚地说明了“itemconfig()”的功能。 (2认同)