簡體   English   中英

Tkinter 如何更改 treeview 所選項目的顏色

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

一個 go 如何更改 treeview 中選定的文本顏色,我似乎在這個主題上找不到太多。

這是我嘗試過的,但顏色並沒有像我想要的那樣變成紅色,它保持藍色。

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

選定的背景顏色不是使用selectbackground選項設置的,而是作為background選項的動態值。 因此,要設置此選項,您需要更換

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

經過

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

這意味着當該項目處於“已選擇”state 時,其背景為紅色。 例如,這也可用於設置禁用的背景顏色。

您可以在此處找到有關動態外觀更改的更多信息: https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/ttk-map.ZFC35FDC70D2269D2698883A

您還可以使用style.map('Treeview')style.map('Treeview', 'background')查詢當前動態值(僅獲取背景值的列表)。

順便說一句,正如 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