Skip to content
Advertisement

Scrollable frame class in tkinter

I have implemented my own scrollable frame class in tkinter:

JavaScript

This works fine, but the problem is to add widgets to the scrolled frame, the parent has to be exampleFrame.content. I have looked at several other examples which all have the same limitation. Is it possible to configure the class so exampleFrame can be the parent of the widgets instead of exampleFrame.content? Thanks in advance.

Advertisement

Answer

If you don’t mind a little trickery, you can simulate what you want. It’s a bit of a hack though.

The trick is that when you call tk.Frame.__init__, you need to be giving it the canvas as the parent, making self the content frame. Of course, to do that you have to create the canvas first, and to create the canvas you have to create the outer frame.

It looks something like this:

JavaScript

However, when you do the above and you try to call pack, place, or grid on the instance of scrolledFrame it’s going to do the wrong thing since the instance points to the inner frame rather than the outer frame.

Here’s the trickery: the solution to that is to redirect calls to pack, place, and grid to the outer frame.

JavaScript

With that, you can use scrolledFrame like you want, as long as you use pack, place, or grid when adding it to the layout.

JavaScript

Here’s a complete working example, though I’ve removed the mousewheel code for brevity.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement