6
votes

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.

2
Did you try self.tree.tag_configure('oddrow', background='lightgrey', selectbackground='blue') ?Steven Rumbalski
@StevenRumbalski: _tkinter:TclError: unknown option "-selectbackground"foosion
Just read the docs at tcl.tk/man/tcl/TkCmd/ttk_treeview.htm#M69. tag only supports foreground, background, font, and image. Sorry for the bad advice.Steven Rumbalski
No worries. Thanks for tryingfoosion

2 Answers

4
votes

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.

1
votes

If anyone looking for an answer to change selected color for tkinter treeview, you can check below code.

You have change the state "selected" rather than "active".

style = ttk.Style()
style.configure("Treeview",
                background="#E1E1E1",
                foreground="#000000",
                rowheight=25,
                fieldbackground="#E1E1E1")
style.map('Treeview', background=[('selected', '#BFBFBF')])