0
votes

I have been trying to create an application using Tkinter module for Python 3.4.2 There are N number of labels. For each of these N number of labels, I am trying to create a row of Textboxes which might/might not be of the same length. The number of Textboxes for each label might be different too. I need a scrollbar for this window. So I created a canvas and used Scrollbar widget to create the horizontal and vertical scrollbar. In this canvas, I entered a frame so that I could add my labels and Textboxes. To construct Textboxes of varying lengths I used grid() method for the widgets. I read that the grid columns are of length enough to accommodate the largest widget(here it is a Textbox) and you can't add multiple widgets in a cell of the grid.

I used columnspan property of the Textbox widget but was of no help. e1.grid(row=i, column=1, columnspan=width) for the first column and e1.grid(row=i, column=width_sum, columnspan=width) for the subsequent columns. Here width_sum is the sum of length of different textboxes because of the present one. The width_sum parameter is reset for every Label (which is present in a different row).

I need output something like this:

enter image description here

Thanks in advance.

1

1 Answers

1
votes

To realize the GUI you describe, I think your best option is to:

  • Create 1 frame per row.
  • Then in each frame, use the .pack() geometry manager to pack the textboxes side by side.

enter image description here

Code:

import tkinter as tk
from random import randint

root = tk.Tk()

# Create N frames on top of each other
N = 4 
frames = []
for n in range(N):
    frame = tk.Frame(root)
    frame.pack(side='top', anchor='w')
    # Store the current frame reference in "frames"
    frames.append(frame)

# Add some widgets in each frame
entryboxes = {frame: [] for frame in frames}
for i, frame in enumerate(frames):
    # Add a label
    label = tk.Label(frame, text="Label "+str(i+1))
    label.pack(side='left')
    # Add 5 Entry boxes with random widths
    for i in range(5):
        random_width = 10 + randint(0,9)
        e = tk.Entry(frame, width = random_width)
        e.pack(side='left')
        # Store the current entrybox reference in "entryboxes"
        entryboxes[frame].append(e)

# Add some text in the 4th box of the 3rd frame
entryboxes[frames[2]][3].insert(0, 'hello')

# Launch the app
root.mainloop()