Skip to content

Instantly share code, notes, and snippets.

Created December 14, 2018 16:14
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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():
# 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
def addNewLabel():
global i
tk.Label(fTable, text="Hello World").grid(row=i, column=i)
# Update the scroll region after new widgets are added
root.after(1000, addNewLabel)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment