在Listbox控件中给特定项上色可以吗?

16 投票
1 回答
27632 浏览
提问于 2025-04-16 13:56

我在说的是Listbox这个小工具里的一个特定元素。

我最希望能给背景上色,不过如果能给某个特定的单元格上色,那就太棒了。

1 个回答

48

根据 effbot.org 的文档,关于 Listbox 这个小部件,你不能改变特定项目的颜色:

列表框只能包含文本项目,所有项目必须使用相同的字体和颜色。

但实际上,你可以通过使用 itemconfig 方法来改变特定项目的字体和背景颜色。下面是一个例子:

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

撰写回答