简体   繁体   English

Tkinter 如何更改 treeview 所选项目的颜色

[英]Tkinter how to change the color of treeview selected items

How does one go about changing the selected text color in treeview, I can't seem to find much on the subject.一个 go 如何更改 treeview 中选定的文本颜色,我似乎在这个主题上找不到太多。

Here is what I have tried but the color doesn't change to red as I would like, it stays blue.这是我尝试过的,但颜色并没有像我想要的那样变成红色,它保持蓝色。

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() 

The selected background color is not set with a selectbackground option but as a dynamic value of the background option.选定的背景颜色不是使用selectbackground选项设置的,而是作为background选项的动态值。 Therefore to set this option you need to replace因此,要设置此选项,您需要更换

style.configure('Treeview', selectbackground='red')

by经过

style.map('Treeview', background=[('selected', 'red')])

Which means that when the item is in 'selected' state, its background is red.这意味着当该项目处于“已选择”state 时,其背景为红色。 This can also be used to set a disabled background color for instance.例如,这也可用于设置禁用的背景颜色。

You can find more information about dynamic appearance change here: https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/ttk-map.html您可以在此处找到有关动态外观更改的更多信息: https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/ttk-map.ZFC35FDC70D2269D2698883A

You can also query the current dynamic values with style.map('Treeview') or style.map('Treeview', 'background') (to get only the list of values for the background).您还可以使用style.map('Treeview')style.map('Treeview', 'background')查询当前动态值(仅获取背景值的列表)。

By the way, as suggested by stovfl, if you also need to change the colors of specific rows, you can have a look at Unable to change background color of treeview in python .顺便说一句,正如 stovfl 所建议的,如果您还需要更改特定行的 colors,您可以查看Unable to change background color of treeview in python

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM