Tkinter 如何更改树视图所选项目的颜色

Dan*_*son 5 python tkinter

如何在树视图中更改选定的文本颜色,我似乎找不到太多关于该主题的信息。

这是我尝试过的,但颜色没有像我想要的那样变成红色,它保持蓝色。

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


class App(Frame):

    def __init__(self, parent):
        super().__init__()
        self.container = Frame.__init__(self, parent)
        style = Style()
        self.tv = None
        self.tree()
        style.configure('Treeview', selectbackground='red')

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

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

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

        tv.insert('python1', '0', 'sub1', text='Sub item 1')
        tv.insert('python1', '1', 'sub2', text='Sub item 2')


def main():
    root = Tk()

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

    root.mainloop()


if __name__ == '__main__':
    main() 
Run Code Online (Sandbox Code Playgroud)

j_4*_*321 5

选定的背景颜色不是通过selectbackground选项设置的,而是作为选项的动态值设置的background。因此要设置此选项,您需要替换

style.configure('Treeview', selectbackground='red')
Run Code Online (Sandbox Code Playgroud)

经过

style.map('Treeview', background=[('selected', 'red')])
Run Code Online (Sandbox Code Playgroud)

这意味着当项目处于“选中”状态时,其背景为红色。例如,这也可用于设置禁用的背景颜色。

您可以在此处找到有关动态外观更改的更多信息:https : //anzeljg.github.io/rin2/book2/2405/docs/tkinter/ttk-map.html

您还可以使用style.map('Treeview')或查询当前动态值style.map('Treeview', 'background')(仅获取背景值列表)。

顺便说一句,正如 stovfl 所建议的,如果您还需要更改特定行的颜色,您可以查看Unable to change background color of treeview in python