I am trying to use ttk.Treeview to make a sortable table (as per Does tkinter have a table widget? and https://www.daniweb.com/software-development/python/threads/350266/creating-table-in-python).
Getting it to work is easy, but I'm having some issues with the styling. The default style for the Treeview heading is black text on a white background, which is fine. However, in my code I'm using:
ttk.Style().configure(".", font=('Helvetica', 8), foreground="white")
to format my GUI. This overarching style also affects the heading of the Treeview widget. Because the default heading background is white, I can not see the text (unless I mouse-over the heading, which turns it light-blue).
Normally, I'd override the style of a widget using a tag to change either the background or foreground, but I can't for the life of me figure out how to adjust the Treeview headers! ttk.Treeview(...) doesn't accept any tags, and ttk.Style().configure("Treeview", ...) has no effect. Only the Treeview items appear to accept tags when using widget.insert(...).
This baffles me, because the overarching ttk.Style().configure(".",...) does affect the Treeview headings, so it should be possible to apply a tag to them.
Does anybody know how to alter the style of a Treeview heading?
Below is a Minimum Working Example. Notice that the tag works for items but not for headings, that the Treeview style has no effect, and that the "." style does have an effect. I'm using Python 2.7 on Windows 7 in case that makes a difference.
from Tkinter import *
import ttk
header = ['car', 'repair']
data = [
('Hyundai', 'brakes') ,
('Honda', 'light') ,
('Lexus', 'battery') ,
('Benz', 'wiper') ,
('Ford', 'tire')]
root = Tk()
frame = ttk.Frame(root)
frame.pack()
table = ttk.Treeview(frame, columns=header, show="headings")
table.pack()
## table.tag_configure('items', foreground='blue')
## ttk.Style().configure("Treeview", background='red', foreground='yellow')
## ttk.Style().configure(".", font=('Helvetica', 8), foreground="white")
for col in header:
table.heading(col, text=col.title(), command=lambda c=col: sortby(table, c, 0))
for item in data:
table.insert('', 'end', values=item, tags=('items',))
def sortby(tree, col, descending):
"""sort tree contents when a column header is clicked on"""
# grab values to sort
data = [(tree.set(child, col), child) \
for child in tree.get_children('')]
# if the data to be sorted is numeric change to float
#data = change_numeric(data)
# now sort the data in place
data.sort(reverse=descending)
for ix, item in enumerate(data):
tree.move(item[1], '', ix)
# switch the heading so it will sort in the opposite direction
tree.heading(col, command=lambda col=col: sortby(tree, col, \
int(not descending)))
root.mainloop()
this works where I am -
style = ttk.Style()
style.configure(".", font=('Helvetica', 8), foreground="white")
style.configure("Treeview", foreground='red')
style.configure("Treeview.Heading", foreground='green') #<----