I'm trying to build a function which opens a file browser and lists the selected files in a scrollable frame. I tried using a scrollable frame class I found on the web which works when I apply it to a very simple case, but does not work when applied inside my file browsing function. The scrollable frame class is written as follows:
class ScrollableFrame(ttk.Frame):
def __init__(self, container, *args, **kwargs):
super().__init__(container, *args, **kwargs)
canvas = tk.Canvas(self)
scrollbar = ttk.Scrollbar(self, orient="vertical", command=canvas.yview)
self.scrollable_frame = ttk.Frame(canvas)
self.scrollable_frame.bind(
"<Configure>",
lambda e: canvas.configure(
scrollregion=canvas.bbox("all")))
canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)
canvas.grid(row=0, column=0)
scrollbar.grid(row = 0, column=1)
and then is applied by:
import os
from tkinter import filedialog,Label,Tk,Entry,Frame,ttk
import tkinter as tk
root = Tk()
browse_frame = Frame(root)
browse_frame.grid(row=0, column=0, columnspan=2)
all_files = []
def browse_files():
#function which opens a file browser and adds selected files to all_files list.
#opens file browser
filename_list = list(filedialog.askopenfilenames(initialdir = '/',
title = "Select Files",
filetypes = (("text files","*.txt"),
("csv files","*.csv"),
("all files","*.*"))))
#adds selected files to all_files list
for i in filename_list:
all_files.append(i)
if len(all_files) >=1:
#build scrollable frame for file names
files = ScrollableFrame(root)
files.grid(column=0, row=3, padx=10, pady=10)
file_label = Label(files, text="Selected Files:", font=("arial", 13))
file_label.grid(column=0, row=0, padx=80, pady=10)
u = 0
while u < len(all_files):
#adds each file name to scrollable frame
file_name = Label(files, text=str(os.path.basename(all_files[u])))
file_name.grid(column=0, row=u+1, padx=5, pady=5)
u+=1
return
browse = ttk.Button(browse_frame, text="browse files", command=browse_files)
browse.grid(column=1, row=0, rowspan=2, padx=50, pady=10)
root.mainloop()
which produces the following result where the file list continues beyond the span of the window and the scrollbar is nonfunctional and small.
image of tkinter window with scrollable frame
Any help is greatly appreciated.