Veitch
Veitch

Reputation: 13

Python tkinter: Canvas scrollbar appears but doesn't work

I've been trying to add a scrollbar to a canvas that contains a single frame, this frame is what holds the widgets. I have added the scroll bar which shows up correctly but it has no effect on the canvas.

area2=Frame(border2,bg="#FAFAFA")
area2.pack(side="top",fill=BOTH,expand=True)

scrollbar=Scrollbar(area2)
scrollbar.pack(side='right',fill=Y)

scrollcanvas=Canvas(area2,height=1500,yscrollcommand=scrollbar.set)
scrollcanvas.pack(side='left',fill=BOTH,expand=True)

scrollcanvasframe=Frame(scrollcanvas)
scrollcanvasframe.pack(side='top',fill=BOTH,expand=False)

v2=IntVar()
Label(scrollcanvasframe,textvariable=v2,bg="#FAFAFA").pack(side="top")

canvas2=Canvas(scrollcanvasframe,width=800,height=566,bg='white')
canvas2.pack(side="top")
canvas3=Canvas(scrollcanvasframe,width=800,height=566,bg='grey')
canvas3.pack(side="top")

scrollbar.config(command=scrollcanvas.yview)
scrollcanvas.config(yscrollcommand=scrollbar.set,scrollregion=(0,0,1000,1500))

I think the issue might have something to do with the scrollregion which is added at the end because the canvas expands to fit the frame it is placed in.

I have also tried looking at various posts here but nothing seems to be helping.

Upvotes: 1

Views: 783

Answers (1)

patthoyts
patthoyts

Reputation: 33193

You are trying to embed a frame which contains various other widgets into a canvas so that you can scroll around. However, after you create the scrollcanvasframe you pack it, with is incorrect. The canvas is a geometry manager in its own right and the correct way to make the canvas manage another widget is to use create_window.

In this case, remove the scrollcanvasframe.pack call and replace as shown:

#scrollcanvasframe.pack(side='top',fill=BOTH,expand=False)
scrollcanvas.create_window((5, 5), window=scrollcanvasframe, anchor=NW)

This creates a place holder for the frame widget in the canvas at position 5,5 and sets the anchor to the top left of the object (by default it is the center). Now the widget is being managed by the canvas and will scroll with any other elements. You can test this by adding a rectangle or line on there and see it scroll too.

The other widgets that you have packed into the scrollcanvasframe are fine. They are being managed by the frame.

Upvotes: 2

Related Questions