Align widgets using a grid between multiple Tkinter LabelFrames

I am trying to create a Tkinter layout that has labels and input fields vertically aligned in several LabelFrame blocks.

Here is some simplified code:

 #!/usr/bin/python from Tkinter import * win = Frame() win.grid(sticky=N+S+E+W) frame_a = LabelFrame(win, text='Top frame', padx=5, pady=5) frame_b = LabelFrame(win, text='Bottom frame', padx=5, pady=5) frame_a.grid(sticky=E+W) frame_b.grid(sticky=E+W) for frame in frame_a, frame_b: for col in 0, 1, 2: frame.columnconfigure(col, weight=1) Label(win, text='Hi').grid(in_=frame_a, sticky=W) Label(win, text='Longer label, shorter box').grid(in_=frame_b, sticky=W) Entry(win).grid(in_=frame_a, row=0, column=1, sticky=W) Entry(win, width=5).grid(in_=frame_b, row=0, column=1, sticky=W) win.mainloop() 

In the above code, a window is created that looks like this:

Incorrect image produced by above code

While I'm looking to find a way to align the margins so that the window looks bigger (thanks to MS Paint):

Desired image

I played with in_ arguments before grid() , but didn't achieve very much, and I can't think of anything else to experiment with.

+4
source share
2 answers

The short answer is: you cannot do what you want. grid does not manage its rows and columns in multiple containers.

However, there are at least several ways to achieve the desired effect. One way is to give the first column in each container an explicit, identical width. To do this, you can use the grid_columnconfigure method to give each column a minimum width.

Another solution is to provide each label with the same width, which effectively sets the width of the first column to the same (provided that all the columns in each container have the same weight).

+1
source

The easiest way I know to do what you want is to change the Label text variables, and then check len (txt1) to len (txt2) and set the width variable as the longest one. The following code is close. My knowledge is too limited to figure out where the extra space comes from.

  txt1 = StringVar() txt2 = StringVar() lblWidth = IntVar() txt1 = "Hi" txt2 = "Longer label, shorter box" if (len(txt1) > len(txt2)): lblWidth = len(txt1) else: lblWidth = len(txt2) Label(win, text=txt1, width=lblWidth, anchor=W).grid(in_=frame_a) Label(win, text=txt2, width=lblWidth, anchor=W).grid(in_=frame_b, sticky=W) 
+1
source

Source: https://habr.com/ru/post/1402103/


All Articles