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标题的默认样式是白色背景上的黑色文本,这很好。但是,在我的代码中,我正在使用:
1 | 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以防万一。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | 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() |
这在我所在的地方有效-
1 2 3 4 | 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标头中使用的字体。
例如:
1 | font.nametofont('TkHeadingFont').configure(size = 15) |