Search code examples
pythonexceluser-interfacetkintertreeview

How to solve treeview going out of parent frame in python with tkinter?


I want to load and modify the contents of the Excel sheets. I am using tkinter treeview for displaying data with openpyxl.

The problem is whenever I open the excel sheet larger than the frame size, it goes out of the window and cannot be seen. I used a scrollbar hoping that I could scroll through the data with it, but that also is not working.

Below is test code for this test purpose only:

from tkinter import *
from tkinter import ttk
import openpyxl

file_name = "test1.xlsx"

def open_excel(file_name):
    wb = openpyxl.load_workbook(file_name)
    sheet = wb.active
    list_values = list(sheet.values)

    bom_tree.delete(*bom_tree.get_children())

    bom_tree["column"] = list(list_values[0])
    for col in list_values[0]:
        bom_tree.column(col, stretch=NO, minwidth=25, width=200)
        bom_tree.heading(col, text=col)

    for val in list_values[1:]:
        # print(val)
        bom_tree.insert('', "end", values=val)

root= Tk()
root.title('test2')
root.geometry("1000x600")

#create treeview frame
tree_frame= LabelFrame(root, text="tree frame" ,padx=50, pady=50, width=1000)
tree_frame.pack(padx=20,pady=20)

bom_tree = ttk.Treeview(tree_frame, show="headings", height=10)
bom_tree.grid(row=0,column=0, padx=10)

#scroll bars
tree_scroll_vertical = ttk.Scrollbar(tree_frame, orient=VERTICAL, command=bom_tree.yview)
tree_scroll_vertical.grid(row=0,column=1, sticky=NS)
bom_tree.configure(yscrollcommand=tree_scroll_vertical.set)
tree_scroll_horizontal = ttk.Scrollbar(tree_frame, orient=HORIZONTAL, command=bom_tree.xview)
tree_scroll_horizontal.grid(row=1,column=0, sticky=EW)
bom_tree.configure(xscrollcommand=tree_scroll_horizontal.set)

open_excel(file_name)

root.mainloop()

Here is a screenshot of the output:

enter image description here

I am using grid as it will be required for my application, but I also tried to use packing and still am not able to find the right setting.


Solution

  • Since the treeview is put at column 0, you can add tree_frame.grid_columnconfigure(0, weight=1) to make the treeview to fit into available horizontal space.

    Result:

    enter image description here