Home > Software engineering >  Forcing a TK tree to fit in a window/canvas with scrollbar python 3.9
Forcing a TK tree to fit in a window/canvas with scrollbar python 3.9

Time:02-23

I have a TK treeview that has quite a few columns that I simply wish to put in a LabelFrame with a horizontal scrollbar. I have been through a ton of similar questions and nothing seems to be working. In each case, the tree extends off the edge of the window along with the scrollbar. I would like the displayed tree to fill the labelFrame, with a scrollbar at the bottom allowing the user to scroll left and right to view everything, and/or resize the window if their monitor is big enough. For clarity, I will say that I do not care how wide the table is, so long as the user can scroll left and right within either the default or a resized window.

I cannot put every permutation I've tried here, but this is a minimal example. I have tried with and without a canvas (though I believe I was doing that incorrectly), putting in a LabelFrame, pack_propagate(0), ordering the grid commands, etc.

import tkinter as tk
from tkinter import ttk

#mainWindow is the primary form, this is a secondary window

recentWindow = tk.Tk() #replace the line below to run without mainWindow and add
#mainWindow.mainloop()

#recentWindow = tk.TopLevel(mainWindow)
recentWindow.geometry('800x300')

frmtreeborder = tk.LabelFrame(recentWindow,text='Recent')
recentWindow.pack_propagate(0) #added later for testing, tried with frmtreeborder too
#also tried grid_propagate

#Tried putting the grid statements below for everything but the tree here
#Also tried moving the scrollbar definition here
tree = ttk.Treeview(frmtreeborder,columns=colnames,show='headings',
    height=5,selectmode='extended')

#Populate a colnames just for the example to run
colnames = []
for ii in range(0,20):
    colnames.append(str(ii))
    
for a in colnames:
    tree.column(a,width=85)
    tree.heading(a,text=a)

frmtreeborder.grid(column=0,row=0,sticky='nsew',padx=6,pady=6)
scrollbar = ttk.Scrollbar(recentWindow,orient=tk.HORIZONTAL,command=tree.xview)
tree.configure(xscrollcommand=scrollbar.set)
scrollbar.grid(row=1,column=0,sticky='nw') #if 'new' the scrollbar is the same width as the tree
#Also moved the scrollbar outside the labelFrame to see if that helped
tree.grid(column=0,row=0,sticky='nsew',padx=6,pady=6) #also tried pack

The resulting window. What is not shown is that if the scrollbar is given sticky='nsew' it is the same width as the tree. This makes sense in retrospect, though it implies that everything is dynamically resized since order doesn't seem to matter. I'll note that I am a bit in the Monte Carlo regime of testing, so I may have muddled something up during that process. resulting window

Running python 3.9.7 (Anaconda)

Some unsuccessful threads:

enter image description here

  • Related