Add mouse wheel scrolling to a frame with both vertical and horizontal scrollbars
18:30 15 May 2026
import tkinter as tk

root = tk.Tk()
root.geometry("400x300")

outer_frame = tk.Frame(root)
outer_frame.pack(fill="both", expand=True)

vertical_scrollbar = tk.Scrollbar(outer_frame, orient="vertical")
vertical_scrollbar.pack(side="right", fill="y")
horizontal_scrollbar = tk.Scrollbar(outer_frame, orient="horizontal")
horizontal_scrollbar.pack(side="bottom", fill="x")

canvas = tk.Canvas(outer_frame)
canvas.pack(side="left", fill="both", expand=True)
canvas.configure(yscrollcommand=vertical_scrollbar.set)
canvas.configure(xscrollcommand=horizontal_scrollbar.set)

inner_frame = tk.Frame(canvas)
inner_frame.bind("", lambda event: canvas.configure(scrollregion=canvas.bbox("all")))
canvas.create_window((0, 0), window=inner_frame, anchor="nw")

vertical_scrollbar.configure(
    command=lambda *args, **kwargs: None
    if canvas.bbox("all")[3] <= canvas.winfo_height()
    else canvas.yview(*args, **kwargs),
)
horizontal_scrollbar.configure(
    command=lambda *args, **kwargs: None
    if canvas.bbox("all")[2] <= canvas.winfo_width()
    else canvas.xview(*args, **kwargs),
)
horizontal_scrollbar.update()
vertical_scrollbar.pack_configure(pady=(0, horizontal_scrollbar.winfo_height()))

# count_x, count_y = 1, 1
# count_x, count_y = 100, 1
# count_x, count_y = 1, 100
count_x, count_y = 100, 100
for i in range(count_y):
    text = " ".join(f"Label{i + 1}" for _ in range(count_x))
    tk.Label(inner_frame, text=text).pack(side="top", anchor="nw")

root.mainloop()

Depending on the values for count_x and count_y, the example window will look sometime like this:

screenshot

In all four scenarios

  • no scroll,
  • only vertical scroll,
  • only horizontal scroll,
  • and both vertical and horizontal scroll,

scrolling (or not scrolling) through the frame contents by using the scrollbars works as expected. That includes scrolling via mouse wheel (or scrolling via Shift plus mouse wheel in case of the horizontal scrollbar).

However, scrolling via mouse wheel does not work if the cursor is not hovering the respective scrollbar.

python tkinter scrollbar