Search code examples
pythontkintertreeviewttkttkwidgets

How to only allow the top frame verticaly stretch


I try to adopt Tkinter, treeview doesn't resize with window, with verry little modification.

import tkinter as tk
from tkinter import ttk
import random 

class App():

    def __init__(self):

        self.root = tk.Tk()

        self.frame = tk.Frame(self.root)
        self.frame.pack(expand=True, fill=tk.BOTH)

        self.tree = ttk.Treeview(self.frame, show="headings")
        self.tree.pack(expand=True, )

        self.frameBT = tk.LabelFrame(self.root,text='Buttons')
        self.frameBT.pack(expand=True, fill=tk.X)

        self.button = ttk.Button(self.frameBT, text="Fill", command=self.fill)
        self.button.pack(side=tk.BOTTOM,expand=True)

        self.fill()

        self.root.mainloop()

    def fill(self):

        if self.has_data():
            self.tree.delete(*self.tree.get_children())

        i = random.randrange(1,10)
        self.tree["columns"]=tuple([str(i) for i in range(i)])

        for col in self.tree['columns']:
            self.tree.heading(col, text="Column {}".format(col), anchor=tk.CENTER)
            self.tree.column(col, anchor=tk.CENTER)

        j = random.randrange(10)

        for j in range(j):

            self.tree.insert("", "end", values = tuple([k for k in range(i)]))

    def has_data(self):

        has_tree = self.tree.get_children()

        return True if has_tree else False


App()

Currently, when I stretch the window verticaly, I got

enter image description here

My question is, how to keep that 'Button' at the verry bottom, while the bottom of treeview frame move up and down when I resize the main window.


Solution

  • You need to:

    • make self.tree to fill all available space by setting fill=tk.BOTH:
    self.tree.pack(expand=True, fill=tk.BOTH)  # added fill=tk.BOTH
    
    • disable expand of self.frameBT by removing expand=True:
    self.frameBT.pack(fill=tk.X)  # removed expand=True