Reputation: 532
I'm still trying to figure out Tkinter and I don't understand why this right
variable doesn't show up all the way to the right? I thought these frames would divide the window vertically, no?
from tkinter import *
root = Tk()
frame1 = Frame(root, bg = 'blue').grid(row = 0, column =0,sticky = W)
Label(frame1, text = 'Left').grid(row = 0, column =0,sticky = W)
frame2 = Frame(root, bg = 'blue').grid(row = 0, column = 1,sticky = E)
Label(frame2, text = 'Right').grid(row = 0, column =1,sticky = E)
root.mainloop()
Upvotes: 0
Views: 617
Reputation: 10979
Nae's answer is correct but it didn't quite work when I tried it. The reason is that
frame1 = Frame(root, bg = 'blue').grid(row = 0, column =0,sticky = W)
binds the name frame1
to the returned value of .grid(), which is None. When you execute this line:
Label(frame1, text = 'Left').grid(row = 0, column =0,sticky = W)
you are, in effect, making the label a top-level window because its parent is None rather than the Frame.
This worked for me (python3.6 on Windows 10):
from tkinter import *
root = Tk()
frame1 = Frame(root, bg = 'blue')
frame1.grid(row = 0, column =0, sticky = W)
Label(frame1, text = 'Left').grid(row = 0, column = 0)
frame2 = Frame(root, bg = 'green')
frame2.grid(row = 0, column = 1,sticky = E)
Label(frame2, text = 'Right').grid(row = 0, column = 0)
root.columnconfigure(0, weight=1)
root.columnconfigure(1, weight=1)
root.mainloop()
To elaborate on the explanation of columnconfigure: by default, tk squeezes the grid into the minimum possible space, even if that doesn't fill the window. So the two labels end up squeezed to the left. Even though the second one has sticky=E, there's no extra space in the layout so you don't see the effect of the sticky setting. You override this by assigning a non-zero weight to one or more columns. That tells tk to expand the grid until it fills the window by allocating the unused space based on the relative column weights.
Upvotes: 2
Reputation: 15345
try adding:
Grid.rowconfigure(root, 0, weight=1)
Grid.columnconfigure(root, 0, weight=1)
Grid.columnconfigure(root, 1, weight=1)
just before
root.mainloop()
optionally you can add the below alone for some reason:
Grid.columnconfigure(root, 0, weight=1)
I think the reason your code doesn't seem to work as you wanted is somehow root window refusing to shrink it's width more than that. If you have longer texts or larger fonts it works as you intended it to.
Upvotes: 1