2.11 pack grid place placement location
pack
First, let’s take a look at our commonly used pack(), which will be arranged up, down, left, and right.
tk.Label(window, text='1').pack(side='top')#上
tk.Label(window, text='1').pack(side='bottom')#下
tk.Label(window, text='1').pack(side='left')#左
tk.Label(window, text='1').pack(side='right')#右
Next we will look at gridgrid()
. Grid is a grid, so all content will be placed in these regular grids.
for i in range(4):
for j in range(3):
tk.Label(window, text=1).grid(row=i, column=j, padx=10, pady=10)
The above code creates a table with four rows and three columns, which grid
is actually positioned in the form of a table. The parameters here row
are rows and colum
columns, padx
which are the left and right spacing of cells, pady
and the top and bottom spacing of cells.
place
and then the next step is place()
, this is easier to understand, it is to give precise coordinates to position, as given here (20,10)
, it is to place this component at (x,y)
the coordinates of the parameter behind the position anchor=nw
, which is the anchor point mentioned earlier, which is the northwest corner.
tk.Label(window, text=1).place(x=20, y=10, anchor='nw')
Code
import tkinter as tk
window = tk.Tk()
window.geometry('200x200')
#canvas = tk.Canvas(window, height=150, width=500)
#canvas.grid(row=1, column=1)
#image_file = tk.PhotoImage(file='welcome.gif')
#image = canvas.create_image(0, 0, anchor='nw', image=image_file)
#tk.Label(window, text='1').pack(side='top')
#tk.Label(window, text='1').pack(side='bottom')
#tk.Label(window, text='1').pack(side='left')
#tk.Label(window, text='1').pack(side='right')
#for i in range(4):
#for j in range(3):
#tk.Label(window, text=1).grid(row=i, column=j, padx=10, pady=10)
tk.Label(window, text=1).place(x=20, y=10, anchor='nw')
window.mainloop()