Skip to content

Instantly share code, notes, and snippets.

@josephhutch
Created December 14, 2018 16:14
Show Gist options
  • Save josephhutch/5fafbbe66db2e695a246fa99306b0420 to your computer and use it in GitHub Desktop.
Save josephhutch/5fafbbe66db2e695a246fa99306b0420 to your computer and use it in GitHub Desktop.
Tkinter: Adding scrollbars to a container that changes size or is dynamically sized
import tkinter as tk
root = tk.Tk()
# Tkinter widgets needed for scrolling. The only native scrollable container that Tkinter provides is a canvas.
# A Frame is needed inside the Canvas so that widgets can be added to the Frame and the Canvas makes it scrollable.
cTableContainer = tk.Canvas(root)
fTable = tk.Frame(cTableContainer)
sbHorizontalScrollBar = tk.Scrollbar(root)
sbVerticalScrollBar = tk.Scrollbar(root)
# Updates the scrollable region of the Canvas to encompass all the widgets in the Frame
def updateScrollRegion():
cTableContainer.update_idletasks()
cTableContainer.config(scrollregion=fTable.bbox())
# Sets up the Canvas, Frame, and scrollbars for scrolling
def createScrollableContainer():
cTableContainer.config(xscrollcommand=sbHorizontalScrollBar.set,yscrollcommand=sbVerticalScrollBar.set, highlightthickness=0)
sbHorizontalScrollBar.config(orient=tk.HORIZONTAL, command=cTableContainer.xview)
sbVerticalScrollBar.config(orient=tk.VERTICAL, command=cTableContainer.yview)
sbHorizontalScrollBar.pack(fill=tk.X, side=tk.BOTTOM, expand=tk.FALSE)
sbVerticalScrollBar.pack(fill=tk.Y, side=tk.RIGHT, expand=tk.FALSE)
cTableContainer.pack(fill=tk.BOTH, side=tk.LEFT, expand=tk.TRUE)
cTableContainer.create_window(0, 0, window=fTable, anchor=tk.NW)
# Adds labels diagonally across the screen to demonstrate the scrollbar adapting to the increasing size
i=0
def addNewLabel():
global i
tk.Label(fTable, text="Hello World").grid(row=i, column=i)
i+=1
# Update the scroll region after new widgets are added
updateScrollRegion()
root.after(1000, addNewLabel)
createScrollableContainer()
addNewLabel()
root.mainloop()
@maiabm
Copy link

maiabm commented Jul 9, 2024

I'm writing to express my many thanks for uploading this. I've been agonizing over dynamically updating the scroll bar region for almost a month now, and this is the first time I've come across the .update_idletasks() method. I had everything else figured out up till that point, and if I hadn't found this bit of code I would probably have given up!!
Thanks again!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment