import numpy as np
import tkinter as tk
from tkinter import ttk
resultado = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
root = tk.Tk()
frame_labelr = ttk.Frame(root)
frame_labelr.pack(fill=tk.BOTH, expand=True)
# ============================================================================== #
##############################################################################
tree = ttk.Treeview(frame_labelr)
tree.pack(side=tk.LEFT, expand=True, fill=tk.BOTH)
scrollbar = ttk.Scrollbar(frame_labelr, orient=tk.VERTICAL, command=tree.yview)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
tree.configure(yscrollcommand=scrollbar.set)
n_filas, n_columnas = resultado.shape
columns = ["Filas"] + [f"Col {iindex}" for iindex in range(1, n_columnas + 1)]
# Asignar las columnas al Treeview
tree["columns"] = columns
# Formatear columnas
for index, column in enumerate(columns):
tree.column(f"#{index}", anchor=tk.CENTER, width=40, stretch=tk.NO)
tree.heading(f"#{index}", text=column)
# Insertar datos
for iindex, row in enumerate(resultado):
tree.insert("", tk.END, text=itext=index, values=(*row,))
# ============================================================================== #
root.mainloop()
O tambiénNota: el código que te interesa es el encerrado entre las lineas
# ===...=== #
, el resto es solo para hacer el ejemplo fácilmente reproducible.
También puedes ocultarla mediante el argumento/atributo show
de TreeView
y proceder como hacías antes:
import numpy as np
import tkinter as tk
from tkinter import ttk
resultado = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
root = tk.Tk()
frame_labelr = ttk.Frame(root)
frame_labelr.pack(fill=tk.BOTH, expand=True)
# ============================================================================== #
##############################################################################
tree = ttk.Treeview(frame_labelr, show="headings")
tree.pack(side=tk.LEFT, expand=True, fill=tk.BOTH)
scrollbar = ttk.Scrollbar(frame_labelr, orient=tk.VERTICAL, command=tree.yview)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
tree.configure(yscrollcommand=scrollbar.set)
n_filas, n_columnas = resultado.shape
columns = ["Filas"] + [f"Col {iindex}" for iindex in range(1, n_columnas + 1)]
# Asignar las columnas al Treeview
tree["columns"] = columns
# Formatear columnas
for index, column in enumerate(columns):
tree.column(f"#{index + 1}", anchor=tk.CENTER, width=40)
tree.heading(f"#{index + 1}", text=column)
# Insertar datos
for iindex, row in enumerate(resultado):
tree.insert("", tk.END, values=(iindex, *row))
# ============================================================================== #
root.mainloop()