1

I am trying to place multiple frames on a tkinter canvas. I want them to be scrollable and this post really helped:

Adding a scrollbar to a group of widgets in Tkinter

One thing I am not able to figure out is how do I determine the (x,y) coordinates that have to be specified in the create_window() function.

Each frame has variable number of rows in it, so the height of each frame varies. I wanted to have an equal spacing between adjacent frames. For this, I wanted to determine the height of each frame so that I could specify something like this in the for loop: y_cord = y_cord + frame_height + spacing

I have searched a lot, but was not able to find any method that would give me the height of the frame once all widgets are placed on it. I use the grid() manager for the frame, and the winfo_reqheight() method returns 1 for all frames.

I am really puzzled. Any help would be appreciated.

Community
  • 1
  • 1
mankal
  • 11
  • 2

1 Answers1

0

i was just doing this yesterday, assuming every item in each row or column would be the same width.height as the other items in the same row/column you can build it up row by row or column by column and make an index of the coords.

the way i did this was to create the first window at (0,0) and anchor "nw" then when you call canvas.bbox(tkinter.ALL) it gives you the bounding box of all widgets on the canvas, so if you start by building up the first row you would get a tuple returned of which the 3rd item (index 2) would be where that first item ends. you can then place your next window at (result, 0) and build across the canvas.

you can then repeat this going down the canvas to do the rest of the rows.

an extract of the code i used is below, this was simple making a table of entry widgets on a scrollable canvas.

    xposlist = []
    for row in self.data:
        size = self.canvas.bbox(tk.ALL)
        try:
            y = size[3]+1
        except TypeError:
            y = 0
        for index in range(0, len(row)):
            if len(xposlist) < len(row):
                size = self.canvas.bbox(tk.ALL)
                try:
                    x = size[2]+1
                except TypeError:
                    x = 0
                xposlist.append(x)
            else:
                x = xposlist[index]

            entry = tk.Entry(self.canvas, disabledbackground="white", disabledforeground="black")
            data = row[index]
            if data != "": entry.insert(0, data)
            entry.configure(state="disabled")
            self.canvas.create_window((x,y), anchor="nw", window= entry)

once you have added all your widgets make sure to update your scroll region so it scrolls correctly. one this i usually try to do is if the bbox returns an area smaller than the size the canvas is being displayed then i set the scroll region to match the visible size, this prevents being able to scroll up when the canvas is mostly empty.

James Kent
  • 5,763
  • 26
  • 50