scrollable canvas in tkinter

Solutions on MaxInterview for scrollable canvas in tkinter by the best coders in the world

showing results for - "scrollable canvas in tkinter"
Clara
14 Jan 2021
1import tkinter as tk
2from tkinter import ttk
3
4root = tk.Tk()
5container = ttk.Frame(root)
6canvas = tk.Canvas(container)
7#create canvas in the container frame
8scrollbar = ttk.Scrollbar(container, orient="vertical", command=canvas.yview)
9#create scrollbar in container frame
10scrollable_frame = ttk.Frame(canvas)
11#define the scrollable frame in canvas 
12
13scrollable_frame.bind(
14    "<Configure>",
15    lambda e: canvas.configure(
16        scrollregion=canvas.bbox("all")
17    )
18)
19
20canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
21#this is due that methods: pack(), place() and grid() can't be used for scrollbars
22#so a windows containing scrollable_frame is created in canvas 
23
24canvas.configure(yscrollcommand=scrollbar.set)
25
26
27for i in range(50):
28    ttk.Label(scrollable_frame, text="Sample scrolling label").pack()
29
30container.pack()
31canvas.pack(side="left", fill="both", expand=True)
32scrollbar.pack(side="right", fill="y")
33
34root.mainloop()
35