首页 > 解决方案 > 如何正确设置树视图行前景色和背景色

问题描述

我在为 ttk.Treeview 设置前景色和背景色时遇到问题。

我曾尝试使用 tag_configure 但这似乎也不起作用。我有一些模型代码(如下)我用来解决这个问题。可以更改标题颜色但不能更改行,不确定我做错了什么。

from tkinter import *
from tkinter.ttk import Treeview, Style


class App(Frame):

    def __init__(self, parent):
        super().__init__()
        self.container = Frame.__init__(self, parent)

        self.tree()

    def tree(self):
        style = Style()

        tv = Treeview(self.container)
        tv.grid(sticky='NSEW')

        tv.insert('', '0', 'item1', text='Item 1', tags='row')
        tv.insert('', '1', 'item2', text='Item 2', tags='row')
        tv.insert('', '2', 'item3', text='Item 3', tags='row')

        tv.insert('item1', '0', 'python1', text='Python Treeview1')
        tv.insert('item1', '1', 'python2', text='Python Treeview2')

        tv.insert('python1', '0', 'thon1', text='Treeview1')
        tv.insert('python1', '1', 'thon2', text='Treeview2')

        tv.heading(f'#{0}',  text='Title')
        style.configure(
            "Treeview.Heading",
            padding=5,
            borderwidth=0,
        )

        style.configure(
            "Treeview",
            foreground='red',
            background="black",
            fieldbackground='blue'
        )
        tv.tag_configure('row', foreground='red')


def main():
    root = Tk()

    root.grid_rowconfigure(0, weight=1)
    root.grid_columnconfigure(0, weight=1)
    App(root)

    root.mainloop()


if __name__ == '__main__':
    main()

标签: pythontkinter

解决方案


如来自https://stackoverflow.com/users/7414759/stovfl的评论中所述,Tcl/tk 库中有一个错误。


推荐阅读