【问题标题】:Changing colour of item in Tkinter listbox更改 Tkinter 列表框中项目的颜色
【发布时间】:2016-08-23 04:31:45
【问题描述】:

参考Is it possible to colour a specific item in a Listbox widget? 是否可以根据列表中保存的数据更改bg colour。

例如:

在列表names中有几个值,一些是正的,一些是负的。我想根据它们是正面还是负面来更改它们的背景颜色。

if names > 0 :
    diffbox.itemconfig(bg='red')
if names < 0 :
    diffbox.itemconfig(bg='green')

diffbox.insert(END, names)

【问题讨论】:

    标签: python tkinter listbox


    【解决方案1】:
    itemconfig() 的

    index 参数可以是"end",你应该利用它。先将项目插入end,然后更改其背景。

    import Tkinter as tk
    
    def demo(master):
        listbox = tk.Listbox(master)
        listbox.pack(expand=1, fill="both")
    
        # inserting some items
        for names in [0,1,-2,3,4,-5,6]:
            listbox.insert("end", names)
            listbox.itemconfig("end", bg = "red" if names < 0 else "green")
    
            #instead of one-liner if-else, you can use common one of course
            #if item < 0:
            #     listbox.itemconfig("end", bg = "red")
            #else:
            #     listbox.itemconfig("end", bg = "green")
    
    if __name__ == "__main__":
        root = tk.Tk()
        demo(root)
        root.mainloop()
    

    【讨论】:

    • 非常感谢!很有帮助
    猜你喜欢
    • 2011-10-17
    • 2011-11-22
    • 1970-01-01
    • 2011-07-01
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多