[英]How to change the foreground or background colour of a selected cell in 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.