如何在 Treeview 中编辑标题的样式 (Python ttk)

How to edit the style of a heading in Treeview (Python ttk)

我正在尝试使用 ttk.Treeview 制作 sortable table(根据 Does tkinter have a table widget? and https://www.daniweb.com/software-development/python/threads/350266/creating-table-in-python)。

让它工作很容易,但我在样式方面遇到了一些问题。 Treeview 标题的默认样式是白底黑字,这很好。但是,在我的代码中,我使用的是:

ttk.Style().configure(".", font=('Helvetica', 8), foreground="white")

格式化我的 GUI。这种总体风格也会影响 Treeview 小部件的标题。因为默认的标题背景是白色的,所以我看不到文字(除非我 mouse-over 标题,它会变成 light-blue)。

通常,我会使用标签覆盖小部件的样式以更改背景或前景,但我终究无法弄清楚如何调整 Treeview headers! ttk.Treeview(...) 不接受任何标签,并且 ttk.Style().configure("Treeview", ...) 无效。使用 widget.insert(...).

时,只有 Treeview 项目似乎接受标签

这让我感到困惑,因为总体 ttk.Style().configure(".",...) 确实 影响了 Treeview 标题,所以它应该是可以对它们应用标签。

有人知道如何更改 Treeview 标题的样式吗?

下面是一个最低限度的工作示例。请注意,该标记适用于项目但不适用于标题,Treeview 样式无效,并且“.”风格确实有影响。我在 Windows 7 上使用 Python 2.7 以防有所不同。

    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()

这在我所在的地方有效 -

style = ttk.Style()
style.configure(".", font=('Helvetica', 8), foreground="white")
style.configure("Treeview", foreground='red')
style.configure("Treeview.Heading", foreground='green') #<----

http://www.tkdocs.com/tutorial/styles.html

您可以使用默认命名字体 'TkHeadingFont' 更改 Treeview headers 中使用的字体。

例如:

font.nametofont('TkHeadingFont').configure(size = 15)