在Tkinter中将Treeview的最后两行加粗



我有一个excel范围加载在树视图。我想要的是粗体的最后两行表在树视图。这可能吗?是否也可以改变树视图中特定单元格的颜色,例如我想改变单元格(3,3)的颜色为绿色。

请帮助。这是我的代码。

# Import the required libraries
from tkinter import *
from tkinter import ttk, filedialog
import pandas as pd
# Create an instance of tkinter frame
win = Tk()
df = pd.read_excel('Data.xlsm', sheet_name = 'Differential Pressure',usecols="A:I",header=47,nrows=11)
# Set the size of the tkinter window
win.geometry("900x350")

# Create an object of Style widget
style = ttk.Style()
style.theme_use('clam')
# Add a Treeview widget
my_tree = ttk.Treeview()
my_tree["column"] = list(df.columns)
my_tree["show"] = "headings"
for column in my_tree["column"]:
my_tree.heading(column,text=column)
df_rows=df.to_numpy().tolist()
for row in df_rows:
my_tree.insert("","end",values=row)
my_tree.column("#1",anchor=W, stretch=NO, width=70)
my_tree.column("#2",anchor=W, stretch=NO, width=200)
my_tree.column("#3",anchor=CENTER, stretch=NO, width=60)
my_tree.column("#4",anchor=CENTER, stretch=NO, width=100)
my_tree.column("#5",anchor=CENTER, stretch=NO, width=120)
my_tree.column("#6",anchor=CENTER, stretch=NO, width=60)
my_tree.column("#7",anchor=CENTER, stretch=NO, width=60)
my_tree.column("#8",anchor=CENTER, stretch=NO, width=60)
my_tree.column("#9",anchor=CENTER, stretch=NO, width=60)
my_tree.row("#1",st)
my_tree.pack()
win.mainloop()

您可以更改单个行的样式,但不能更改单个单元格的样式。

然而,在tk 8.6之后的Treeview行样式前景和背景颜色上存在错误,建议临时修复如下:

...
# Create an object of Style widget
style = ttk.Style()
style.theme_use('clam')
def fix_map(option):
return [elm for elm in style.map('Treeview', query_opt=option)
if elm[:2] != ('!disabled', '!selected')]
style.map('Treeview', foreground=fix_map('foreground'),
background=fix_map('background'))
...
现在你可以使用.tag_configure(): 创建样式
my_tree.tag_configure('bold', font=('',0,'bold'), foreground='red')

然后将样式应用到最后两行:

for row in my_tree.get_children()[-2:]:
my_tree.item(row, tags='bold')

最新更新