Tkinter grid rowconfigure() and columnconfigure()
When designing the layout of a widget control, sometimes you will run into the window scaling size, so you can use these two methods to set the scaling of the first few rows or columns.
For example:
rowconfigure(0, weight=1) # row 0 controls have a scaling ratio of 1 when the window changes size
columnconfigure(0, weight=1) # column 0 controls have a scaling ratio of 1 when the window changes size
Tkinter grid rowconfigure() and columnconfigure() Example#1
Recognize the usage of rowconfigure( ), columnf i gure( ), and sticky parameters; the sticky parameter is not used here.
from tkinter import *
root = Tk()
root.title("apidemos.com")
root.rowconfigure(1,weight=1)
root.columnconfigure(0,weight=1)
lab1 = Label(root,text="Label 1",bg="pink")
lab1.grid(row=0,column=0,padx=5,pady=5)
lab2 = Label(root,text="Label 2",bg="lightblue")
lab2.grid(row=0,column=1,padx=5,pady=5)
lab3 = Label(root,bg="yellow")
lab3.grid(row=1,column=0,columnspan=2,padx=5,pady=5)
root.mainloop()
Output:
Results after enlarging the window:
The above program specifically uses the base color to express the space occupied by each label, and the reader can see the space occupied by each control without using the sticky parameter.
Tkinter grid rowconfigure() and columnconfigure() Example#2
Add design Label 1 with sticky=W
so that it can cut flush left. Also allow the tabs below to be aligned top, bottom, left and right.
from tkinter import *
root = Tk()
root.title("apidemos.com")
root.rowconfigure(1,weight=1)
root.columnconfigure(0,weight=1)
lab1 = Label(root,text="Label 1",bg="pink")
lab1.grid(row=0,column=0,padx=5,pady=5,sticky=W)
lab2 = Label(root,text="Label 2",bg="lightblue")
lab2.grid(row=0,column=1,padx=5,pady=5)
lab3 = Label(root,bg="yellow")
lab3.grid(row=1,column=0,columnspan=2,padx=5,pady=5,
sticky=N+S+W+E)
root.mainloop()
Output:
Results after enlarging the window:
The result of the above implementation shows that the tab controls below can be changed with the window size, mainly as a result of setting sticky=N+S+W+E
in line 18. As for line 11, setting sticky=W
will make the lab1 control align to the left.
Tkinter grid rowconfigure() and columnconfigure() Example#3
Enables the Label 1 control to cut left and right flush, while having an expanded effect when zooming in on the window.
from tkinter import *
root = Tk()
root.title("apidemos.com")
root.rowconfigure(1,weight=1)
root.columnconfigure(0,weight=1)
lab1 = Label(root,text="Label 1",bg="pink")
lab1.grid(row=0,column=0,padx=5,pady=5,sticky=W+E)
lab2 = Label(root,text="Label 2",bg="lightblue")
lab2.grid(row=0,column=1,padx=5,pady=5)
lab3 = Label(root,bg="yellow")
lab3.grid(row=1,column=0,columnspan=2,padx=5,pady=5,
sticky=N+S+W+E)
root.mainloop()
Output:
Results after enlarging the window: