0

How can I create buttons and labels in a canvas widget and make the whole set of widgets in the canvas scrollable?

I came across a _create() option in my IDE but I'm not sure how to use it. I tried entering Button for itemType but it didn't work. I tried create_window() but I'm not sure how to use it either.

My question is not how to use a loop and add the buttons, but how can I create widgets and place them in a canvas, but scrollable? Also is there a _create()? If yes, is there any way to create widgets using it?

Nimantha
  • 6,405
  • 6
  • 28
  • 69
The Amateur Coder
  • 789
  • 3
  • 11
  • 33
  • 1
    First of all, you need to make the canvas the parent of the widget then instead of calling `.pack`/`.grid`/`.place` use `.create_window(, , window=, anchor=)`. For more info look [here](http://web.archive.org/web/20201108093851/http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.create_window-method). Also if you just want a scrollable frame use [this](https://stackoverflow.com/a/66215091/11106801) – TheLizzard Jun 29 '21 at 09:26

1 Answers1

2

How to create buttons and labels in a canvas widget and make the whole set of widgets in the canvas scrollable?

You have two choices:

  • use the canvas method create_window to add the buttons and labels to the canvas at specific coordinates
  • use the canvas method create_window to add a frame to the canvas, and then put your buttons and labels inside of the frame using pack or grid or place.

You then have to make sure you configure the scrollregion of the canvas to be large enough to include the widgets.

I came across a _create() option in my IDE but I'm not sure how to use it.

The following example shows how to use create_window to add a button to a canvas. The procedure is the same for any type of widget.

canvas = tk.Canvas(root)
canvas.pack(fill="both", expand=True)

the_button = tk.Button(canvas, text="Click me", ...)
canvas.create_window(10, 10, window=the_button, anchor="nw")
canvas.configure(scrollregion=canvas.bbox("all"))
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685