pandas Python Tkinter Treeview -基于条件单独为行着色

xv8emn3q  于 2023-03-28  发布在  Python
关注(0)|答案(2)|浏览(232)

我正在用tkinter构建一个GUI,想知道是否有办法为满足特定条件的行设置背景颜色。
举个简单的例子:

import numpy as np
import pandas as pd
import tkinter as tk
from tkinter import *
from tkinter import filedialog, ttk

# Data
df = pd.DataFrame(dict(
    A=np.random.randint(1, 6, size=4),
    B=np.random.randint(1, 10, size=4),
    C=np.random.randint(1, 12, size=4),
    D=np.random.randint(1, 9, size=4)
))

# subset of dataframe
df_tree = df[["A","B"]]

# Treeview
root = tk.Tk()
root.title("Example")
root.geometry('600x600')
root.pack_propagate(False)

# Frame for Treeview
TV_frame = tk.LabelFrame(root)
TV_frame.place(height=580, width = 580, rely=0.02, relx=0.02)

# Build Tree with df_tree
Tree = ttk.Treeview(TV_frame)
Tree.place(relheight=0.96, rely=0.01, relx = 0.01, relwidth=0.98)

treescrolly = tk.Scrollbar(TV_frame, orient = "vertical", command = Tree.yview)
treescrollx = tk.Scrollbar(TV_frame, orient = "horizontal", command = Tree.xview)

Tree.configure(xscrollcommand=treescrollx.set, yscrollcommand=treescrolly.set)
treescrollx.pack(side="bottom", fill="x")
treescrolly.pack(side="right", fill="y")

#Print tree in tkinter
Tree["column"] = list(df_tree.columns)
Tree["show"] = "headings"

for column_1 in Tree["columns"]:
    Tree.heading(column_1, text=column_1)

df_rows_1 = df_tree.to_numpy().tolist()

for row_1 in df_rows_1:
    Tree.insert("", "end", values = row_1)

root.mainloop()

例如,我希望C列大于6的所有行的背景都是红色的。有没有办法做到这一点?

5tmbdcev

5tmbdcev1#

insert方法将接受一个名为“tags”的参数。您可以使用它来定义树视图行的颜色。
为此,请将以下行添加到您的代码中,位于打包treeview滚动条的行的下面:

Tree.tag_configure('tag_name', background="red")

这将创建一个标记,您可以使用该标记来影响树视图行的背景颜色。如果要向行添加多种颜色,则可以使用多个标记。在向树中插入行时,可以使用这些标记,如下所示:

Tree.insert("", "end", values = row_1, tags='tag_name')

在你的情况下,你可以做一些像这样的事情:

for row_1 in df_rows_1:
    if column C > 6:
        Tree.insert("", "end", values = row_1, tags='tag_for_red')
    else:
        Tree.insert("", "end", values = row_1, tags='tag_for_other_color')
kknvjkwl

kknvjkwl2#

Tree.tag_configure("tagName", background="Blue")
Tree.item("rowNum", tags=("tagName"))

相关问题