【问题标题】:Is it possible to colour a specific item in a Listbox widget?是否可以为 Listbox 小部件中的特定项目着色?
【发布时间】:2011-07-17 22:25:23
【问题描述】:

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

为背景着色是最理想的,但为特定单元格着色的任何形式都很棒。

【问题讨论】:

    标签: python user-interface colors listbox tkinter


    【解决方案1】:

    根据有关Listbox 小部件的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()
    

    【讨论】:

    • 啊……好的,谢谢。我是 python 新手,我试图使用 .configure(bg="Green")
    • 这个documentation 比较清楚itemconfig() 能做什么。
    猜你喜欢
    • 1970-01-01
    • 2015-08-08
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2022-07-28
    相关资源
    最近更新 更多