【问题标题】:Tkinter how to change the color of treeview selected itemsTkinter如何更改treeview所选项目的颜色
【发布时间】:2019-09-29 22:46:19
【问题描述】:

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

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

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

【问题讨论】:

标签: python tkinter


【解决方案1】:

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

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

通过

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

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

您可以在此处找到有关动态外观更改的更多信息: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

【讨论】:

  • @stovfl 我不明白您的评论,您链接的答案是关于使用标签更改项目背景颜色,而据我了解,OP 的问题是关于选定的行背景颜色。但是,您在评论中链接到该问题的问题确实是相关的。
  • @stovfl 好的,谢谢,我已经在答案中添加了链接
  • 感谢您的回答正是我所需要的。
猜你喜欢
  • 2017-06-19
  • 1970-01-01
  • 2015-01-07
  • 1970-01-01
  • 2015-10-06
  • 1970-01-01
  • 2021-11-10
  • 2021-08-29
  • 2011-07-01
相关资源
最近更新 更多