Search code examples
pythontkintertreeview

Using Multiple Tkinter Treeview Styles in same program


I don't seem to be able to find the answer to this. I am using several Tkinter Treeviews in my program. When I change the style of one, it changes all of them. What Am I missing? This is the code I have written for one, its repeated four times (the others with different colours)

style = ttk.Style()
#style.theme_use("default")
style.configure("Treeview",background="Black", foreground="White",fieldbackground="red")
style.map('Treeview', background=[('selected','#3c3737')],foreground=[('selected','white')])
my_tree = ttk.Treeview(my_canvas2,height=1000)

Solution

  • You can create custom widget styles by using style.configure("<custom_name>.<widget_type>".... So, if you wanted to create a custom "Treevew" style, you would use style.configure("MyCustom.Treeview"...).

    You then would create a ttk widget and pass the custom widget style as the style argument, for example my_treeview = ttk.Treeview(master, style="MyCustom.Treeview"). Here is an example program that creates two different ttk.TreeViews, with different styles:

    import tkinter
    from tkinter import ttk
    
    w = tkinter.Tk()
    
    style = ttk.Style()
    style.configure("Custom1.Treeview",background="Black", foreground="White",fieldbackground="red")
    style.map('Custom1.Treeview', background=[('selected','#3c3737')],foreground=[('selected','white')])
    
    style.configure("Custom2.Treeview",background="Greed", foreground="Purple",fieldbackground="pink")
    style.map('Custom2.Treeview', background=[('selected','#3c3737')],foreground=[('selected','white')])
    
    my_tree1 = ttk.Treeview(w, height=1000, style="Custom1.Treeview")
    my_tree1.pack(side="left")
    
    my_tree2 = ttk.Treeview(w, height=1000, style="Custom2.Treeview")
    my_tree2.pack(side="right")
    
    w.mainloop()