tkinter ttk.Treeview: changing background colour of single item when selected

Thomas Passin list1 at tompassin.net
Sat Feb 4 11:25:09 EST 2023


I haven't worked specifically with a Treeview, but I think you need to 
detect the onClick event (or an onSelect event if there is one) and have 
that trigger the flashing.  Otherwise the selection probably overwrites 
styling that you added. That's what I do for classic Tk buttons to make 
them flash when selected.  (I only flash once, though; I don't keep them 
flashing).

On 2/4/2023 5:42 AM, John O'Hagan wrote:
> Hi list
> 
> I'm using a ttk Treeview to display a hierarchical data structure. When
> an error condition arises in a node, I want the corresponding item in
> the Treeview to flash its background color.
> 
> Using a tag to flash the item background works, except when the item is
> selected, when the tag has no effect. I want the item to keep flashing
> even when selected.
> 
> The code below is a minimal example of the issue. It displays a
> Treeview containing two items with the first one flashing. If you
> select it, you don't see the flashing anymore.
> 
> from tkinter import *
> from tkinter.ttk import *
> 
> root = Tk()
> t = Treeview(root)
> 
> t.insert('', 0, iid='item1', text='item1')
> t.insert('', 1, text='item2')
> t.tag_configure('flashtag', background='red')
> t.pack()
> 
> def flash():
>   tags = t.item('item1', 'tags')
>   t.item('item1', tags='' if tags else 'flashtag')
>   t.after(500, flash)
> 
> flash()
> mainloop()
> 
> Other than tags, the only other way I've found to dynamically change
> Treeview backgrounds is using styles, in particular Style.map to
> configure the background of a selected item, but they apply to all
> items in the Treeview and would flash all selected items, not just the
> one I want to keep flashing.
> 
> Is there another way to do what I want?
> 
> Thanks
> 
> --
> 
> John
> 



More information about the Python-list mailing list