1

I'm trying to change a selected background and foreground color of a row in a Treeview widget, i searched the question have been asked before, but found no explicit answer for it.

Even though question is clear enough but my code is something like this now and not working at all, it won't even change the normal background (as I found, I have to bind the tags for select and deselect events, but tags are not working and nothing changes):

tree = ttk.Treeview(master)
tree.pack()
tree.tag_configure("hi", background="red")
tree.insert("", "end", text="this is a row", tags=("hi",))

any help will be appreciated.

  • ***"won't even change the normal background "***: I got `'red' background`. Can't reproduce this, please make sure, code you posts actually behaves as you claim. – stovfl Mar 29 '20 at 09:55
  • 1
    Does this answer you question? [selected style in Treeview](https://stackoverflow.com/a/60875806/7414759) – stovfl Mar 29 '20 at 10:07
  • @stovfl, Thanks a lot, i tried that code again and no background became red!!, the answer you linked is what I'm looking for, but style.theme_create is affecting my whole ttk widgets and changes them to a different style, how to prevent that? – Esmail Mahjoor Mar 29 '20 at 12:02
  • 1
    ***"`style.theme_create` is affecting my whole ttk widgets"***: That what's `theme` is for. Follow this answer [create a custom ttk style](https://stackoverflow.com/a/44182565/7414759) – stovfl Mar 29 '20 at 12:15

2 Answers2

1

Thanks to @stovfl comment, I found the answer and decided to share it: (even though still didn't figure out why background style doesn't affect anything in my code)

creating a theme will affect entire ttk widgets which wasn't what i wanted, so i inherited the theme from the default theme, found the default theme using this code:

print(ttk.Style().theme_use())

which for me on windows 10 was 'vista', so here is the code to change the background color of selected rows:

style = ttk.Style(master)
style.theme_create("my", "vista",
                           settings={
                               'Treeview': {
                                   'map': {
                                       'background': [('selected', '#ffdddd'), ("!selected", "white")],
                                       'foreground': [('selected', 'black')],
                                       "font": [("", ("", 13))]
                                   }  # end 'map'
                               }  # end 'Treeview'
                           }  # end settings
                           )
style.theme_use("my")
1

I had the same problem on windows 10. Add the follwing lines and tag_configure works as expected

    style = ttk.Style(self)
    aktualTheme = style.theme_use()
    style.theme_create("dummy", parent=aktualTheme)
    style.theme_use("dummy")

program demonstrating the workaround

Lutz
  • 31
  • 5