ttk treeview: selected color

foosion picture foosion · Oct 25, 2011 · Viewed 7.9k times · Source

The selected row of my ttk treeview shows as a dark blue background with the text white.

If I set the color of the row with a tag, for example:

self.tree.item(item, tags=('oddrow'))

and configure the tag as a color, for example:

self.tree.tag_configure('oddrow', background='lightgrey')

and select the oddrow, the background color does not change (it remains lightgrey) while the text changes from black to white. How can I get the selected row background to be dark blue, whether or not the row is tagged with a color?

Rows not tagged display as black on white, or when selected as white on dark blue.

I tried

ttk.Style().configure('Treeview', selectbackground='blue')

but that didn't do anything.

EDIT: I suppose that when I select an item I could re-tag it as not oddrow, then go back when it's un-selected, but that is rather inelegant.

Answer

Matt Fenwick picture Matt Fenwick · Oct 27, 2011

From the TkDocs tutorial for trees, it seems you can:

  • create a tag with the desired colors (for a selected row)

Then, catch the virtual events from the treeview:

  • assign the tag to a row when it gets the focus
  • unassign the tag from the row when it loses focus

Here's the specific paragraph in the documentation I used:

The treeview will generate virtual events "<TreeviewSelect>", "<TreeviewOpen>" 
and "<TreeviewClose>" which allow you to monitor changes to the widget made 
by the user.   You can use the "selection" method to determine the current 
selection (the selection can also be changed from your program). 

Along with some code from the tutorial:

tree.tag_configure('ttk', background='yellow')
tree.tag_bind('ttk', '<1>', itemClicked); # the item clicked can be found via tree.focus()

note: I'm not sure this will work. I'll have to dig up the code to see what I did.