Search code examples
python-3.xtkintertkinter-layout

Place each element in a Listbox widget of tkinter module into separate row cell


I have a Listbox defined as:

listbox1=tk.Listbox(master=frame_1,listvariable=samples_var)

Where samples_var is a tk.StringVar() class that holds a list of, say, samples.
For example:

samples=["A","B","C","D"]
samples_var=tk.StringVar(value=marko.samples)

And then I define tk.Listbox using:

listbox1=tk.Listbox(master=frame_1,listvariable=samples_var)

I place listbox1 on frame_1 widget by invoking grid. I then specify that I want it starting in row=1,column=3 (as other cells to the left and to the top are occupied), and that I want it spanning the number of rows equal to the length of "samples" list. In above example that is 4 (as there are A,B,C,D) in the "samples" list. This should make it so that the ListBox widgets spans exactly len(samples) rows, starting from.

Code:

listbox1.grid(row=1,column=3,rowspan=len(samples),sticky="nsew")

Is there any way to snap each element of a list to its own row?
For example: A would be in row=1,column=3, B would be in row=2, column=3, C would be in row=3, column=3, etc.
I'm doing this to have nice alignment with rest of widgets in columns.


Solution

  • Is there any way to snap each element of a list to its own row?

    No, there is not. Tkinter is simply not designed to work that way. The height of elements in a list is completely independent of the grid that the listbox may be a part of.

    You could try some trickery where you compute the height of a row in the listbox based on the result of the listbox's bbox command, and then try to coerce the height of each row in your grid to the same size, though it seems like a lot more work than it's worth.