david stephen
david stephen

Reputation: 349

How to grid expand resize windows dynamically?

How to dynamically grid adjust with resize?

in this site https://tkdocs.com/tutorial/grid.html, it explains by default each column have 0 weight. it means no expand.

i just set as the site tells. the ratio is 1:2. each pixel label resize = 2 pixel username entry.

but it stay with same size

import tkinter

root = tkinter.Tk()
root.title("Main Window")
root.geometry("100x50")
loginFrame = tkinter.Frame(root, bg="red")

userLabel = tkinter.Label(loginFrame, text="Username")
userEntry = tkinter.Entry(loginFrame)


userLabel.grid(column=0, row=0, sticky= tkinter.W)
userEntry.grid(column=1, row=0, sticky= tkinter.E)

loginFrame.columnconfigure(0, weight=1)
loginFrame.columnconfigure(1, weight=2)
loginFrame.grid()
root.mainloop()

Upvotes: 0

Views: 410

Answers (1)

Derek
Derek

Reputation: 2244

You need to apply rowconfigure and columnconfigure to the root window.

Then apply them to your loginFrame.

Changing sticky will radically alter the behaviour of userLabel and userEntry.


import tkinter

root = tkinter.Tk()
root.title("Main Window")
root.geometry("100x50")

# apply to root is essential
root.rowconfigure(0, weight = 1)
root.columnconfigure(0, weight = 1)

loginFrame = tkinter.Frame(root, bg="red")
loginFrame.grid(row=0, column=0,sticky = tkinter.NSEW)

# now apply to loginFrame
loginFrame.rowconfigure(0, weight = 1)
loginFrame.columnconfigure(0, weight = 1)
loginFrame.columnconfigure(1, weight = 2)

userLabel = tkinter.Label(loginFrame, text="Username")
userEntry = tkinter.Entry(loginFrame)

# experiment by changing sticky 
if False:
    # expand userLabel and userEntry to fill entire loginFrame
    s = tkinter.NSEW
else:
    # confine userLabel and userEntry to change in width only
    s = tkinter.EW

userLabel.grid(column=0, row=0, sticky= s)
userEntry.grid(column=1, row=0, sticky= s)

root.mainloop()

Upvotes: 1

Related Questions