In this TKinter Tutorial we are going to learn creating TKinter Layout, so as i have already said that there are different layouts that you can use in tkinter. for example we have pack, grid and place. The place layout positions widgets using absolute positioning. The pack layout organizes widgets in horizontal and vertical boxes. The grid layout places widgets in a two dimensional grid.
So now let’s create an example, in the first we want to create pack layout, using pack we can align the widgets horizontally and vertically.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
from tkinter import * class Window(Tk): def __init__(self): super(Window, self).__init__() self.title("Tkinter Layout Managment") self.minsize(500,400) self.wm_iconbitmap("myicon.ico") self.create_layout() def create_layout(self): Label(self, text = "Pack Layout Example") Button(self, text = "Not Going To Be Expand").pack() Button(self, text="It Expand And Not Fill X").pack(expand = 1) Button(self, text="Fill X And Expand").pack(fill = X, expand=1) Button(self, text="LEFT").pack(side=LEFT) Button(self, text="RIGHT").pack(side=RIGHT) window = Window() window.mainloop() |
You can see that we have used different versions of pack, using pack you can expand the widget, you can align the widget to the left or to the right.
If you run the code this will be the result.
Now let’s create grid layout, we can use grid layout for aligning widget in row and column. you can use grid for this, in the grid we need to give the column and row number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
from tkinter import * class Window(Tk): def __init__(self): super(Window, self).__init__() self.title("Tkinter Layout Managment") self.minsize(500,400) self.wm_iconbitmap("myicon.ico") self.create_layout() def create_layout(self): Label(self, text = "Grid Layout Example").grid(column = 0, row = 0) Button(self, text = "Not Going To Be Expand").grid(column = 1, row = 1) window = Window() window.mainloop() |
Run the code and this will be the result.
Now let’s use place, using place we can manage our widgets in the x and y position, you can use absolute position or relative position.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
from tkinter import * class Window(Tk): def __init__(self): super(Window, self).__init__() self.title("Tkinter Layout Managment") self.minsize(500,400) self.wm_iconbitmap("myicon.ico") self.create_layout() def create_layout(self): Label(self, text = "Absoulte Position").place(x = 20, y =20) Label(self, text="Relative Position").place(relx = 0.8, rely = 0.9, relwidth=10, anchor = NE) window = Window() window.mainloop() |