0

I am trying to set the background of a Treeview widget based on the answers provided here

The issue with this answer is it only covers global styles. In my code i am using 2-3 Treeviews which each need their own style.

In the code provided I want to set the background of the first Treeview to white, and the second Treeview to black.

MCVE:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

def _fixed_map(option, style):
        return [elm for elm in style.map("Treeview", query_opt=option) if elm[:2] != ("!disabled", "!selected")]

def set_theme(tv, bg, fg):
    style = ttk.Style()
    style.theme_use("clam")
    style.map("Treeview", foreground=_fixed_map("foreground", style), background=_fixed_map("background", style))
    style.configure("Treeview", background=bg, fieldbackground=bg, foreground=fg)
                

tree1 = ttk.Treeview(root)
tree1.pack(side="left", fill="both", expand=True)
for i in range(10):
    tree1.insert("", "end", text=f"t1 Item #{i+1}")
set_theme(tree1, "white", "black")

tree2 = ttk.Treeview(root)
tree2.pack(side="left", fill="both", expand=True)
for i in range(10):
    tree2.insert("", "end", text=f"t2 Item #{i+1}")
set_theme(tree2, "black", "white")

root.mainloop()
Scott Paterson
  • 392
  • 2
  • 17
  • 1
    Did you read the comments section of the accepted answer? – Thingamabobs Jan 07 '22 at 13:35
  • @Thingamabobs yes i did read through them but i dont quite understand. can you just make arbitrary styles by using "sometext.Widget" and adding it as a style, and if so how can the be automated to be used in the code provided without duplicating the style code over and over again? – Scott Paterson Jan 07 '22 at 14:16
  • Yes and there are several ways to achieve it and it depends on what you need in the end. In general you can configure a style, that will be created if it dosent exist already, by using a f-string and a reference to a Widget like `widget = tk.Button(..` and it will have the form of `f"sometext.{widget.winfo_class()}"`. I gathered some source and documentation with additional information in [my answer](https://stackoverflow.com/a/69890743/13629335) on a different question. – Thingamabobs Jan 07 '22 at 14:31

0 Answers0