簡體   English   中英

如何在Treeview中編輯標題的樣式(Python ttk)

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

我正在嘗試使用ttk.Treeview來制作一個可排序的表(根據tkinter 有一個表小部件嗎?https://www.daniweb.com/software-development/python/threads/350266/creating-table-in- python )。

讓它工作很容易,但我在造型上遇到了一些問題。 Treeview標題的默認樣式是白色背景上的黑色文本,這很好。 但是,在我的代碼中,我正在使用:

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

格式化我的GUI。 這種總體風格也會影響Treeview小部件的標題。 因為默認標題背景是白色的,所以我看不到文本(除非我將鼠標懸停在標題上,將其變為淡藍色)。

通常情況下,我會使用標簽覆蓋窗口小部件的樣式來更改背景或前景,但我不能為我的生活找出如何調整Treeview標頭! 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標頭中使用的字體。

例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM