首页 > 解决方案 > tkinter ttk.Treeview 如何更改第一列的背景颜色?

问题描述

我有一个树视图,我会更改唯一第一列#0 的背景颜色。

我尝试使用 tag_configure 方法,但我无法得到我想要的。

在实践中我不能参考第一列,我不明白我是否可以这样做。

特别是我尝试过这样做

 #w is the ttk.Treeview
 #x is a dict....how can i keep a reference to the first column and change background color?
  x = w.column("#0")
  print(type(x),x)
  w.tag_configure(x,  background='gray')

这是一个完整的脚本,有人可以提出一些例子吗?

#!/usr/bin/python3
import tkinter as tk
from tkinter import ttk

class App(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__()


        self.title("Grid")
        self.init_ui()

    def init_ui(self):

        f = ttk.Frame(self, padding=8)

        w = tk.LabelFrame(f,)

        cols = (["#0",'','w',False,50,50],
                ["#1",'First','w',False,50,50],
                ["#2",'Last','w',False,50,50],)

        self.MyGrid = self.get_tree(w, cols,10)

        w.pack(fill=tk.BOTH, expand=1)

        f.pack(fill=tk.BOTH,padx=5, pady=5, expand=1)

        self.set_values()


    def set_values(self,):


        rs = [("CF", 'Bob', 'Dernier'),
              ("2B", 'Ryne', 'Sandberg'),
              ("LF", 'Gary', 'Matthews'),
              ("1B", 'Leon', 'Durham'),
              ("RF", 'Keith', 'Moreland'),]

        for i in rs:
            self.MyGrid.insert('', tk.END,
                                       iid=i[0],
                                       text=i[0],
                                       values=(i[1],i[2]),)            



    def get_tree(self, container, cols, size=None, show=None):

        ttk.Style().configure("Treeview.Heading", font=('Helvetica', 12, 'bold' ))

        headers = []

        for col in cols:
            headers.append(col[1])
        del headers[0]

        if show is not None:
            w = ttk.Treeview(container,show=show)

        else:
            w = ttk.Treeview(container,)

        #how 
        w['columns']=headers
        #x is a dict....how can i keep a reference to the first column and change background color?
        x = w.column("#0")
        print(type(x),x)
        w.tag_configure(x,  background='gray')


        for col in cols:
            w.heading(col[0], text=col[1], anchor=col[2],)
            w.column(col[0], anchor=col[2], stretch=col[3],minwidth=col[4], width=col[5])

        sb = ttk.Scrollbar(container)
        sb.configure(command=w.yview)
        w.configure(yscrollcommand=sb.set)

        w.pack(side=tk.LEFT, fill=tk.BOTH, expand =1)
        sb.pack(fill=tk.Y, expand=1)

        return w        


if __name__ == '__main__':
    app = App()
    app.mainloop()

我读过这个

Tkinter 8.5 参考 45. ttk.Treeview

在此处输入图像描述

标签: pythontkinter

解决方案


推荐阅读