https://realpython.com/python-gui-tkinter/
Grid dzieli okno lub Frame na wiersze i kolumny. Lokalizację widżetu określamy przez wywołanie .grid() i przekazanie indeksów wiersza i kolumny do argumentów 'row' i 'column' (row=i, column=j). Indeksy dla wierszy i kolumn zaczynają się od zera.
Opcja 'sticky' dla grid opisuje jak widżet ma się ułożyć względem komórki siatki.
columnspan=2 # widget ma zająć dwie kolumny na siatce rowspan=2 # widget ma zająć dwia wiersze na siatce sticky=tk.N # "n" or "N" sticky=tk.E # "e" or "E" sticky=tk.S # "s" or "S" sticky=tk.W # "w" or "W" sticky=tk.NE # "ne" or (tk.N, tk.E) sticky=tk.NW # "nw" or (tk.N, tk.W) sticky=tk.SE # "se" or (tk.S, tk.E) sticky=tk.SW # "sw" or (tk.S, tk.W) sticky=tk.EW # "ew" or (tk.E, tk.W) sticky=tk.NS # "ns" or (tk.N, tk.S) sticky=tk.NSEW # "nsew" or (tk.N, tk.S, tk.E, tk.W) +----------------+--------------+ | .grid() | .pack() | +================+==============+ | sticky=tk.NS | fill=tk.Y | +----------------+--------------+ | sticky=tk.EW | fill=tk.X | +----------------+--------------+ | sticky=tk.NSEW | fill=tk.BOTH | +----------------+--------------+
# grid1.py import tkinter as tk root = tk.Tk() for i in range(3): for j in range(3): frame = tk.Frame( master=root, relief=tk.RAISED, borderwidth=1 ) frame.grid(row=i, column=j) label = tk.Label(frame, text="Row {}\nColumn {}".format(i, j)) label.grid() root.mainloop() # run the tkinter event loop
# grid2.py import tkinter as tk root = tk.Tk() for i in range(3): # Expanding window configuration. # Every row and column has to be configured separately. root.columnconfigure(i, weight=1, minsize=75) root.rowconfigure(i, weight=1, minsize=50) for j in range(3): frame = tk.Frame( master=root, relief=tk.RAISED, borderwidth=1 ) frame.grid(row=i, column=j, padx=5, pady=5) # external padding in pixels label = tk.Label(frame, text="Row {}\nColumn {}".format(i, j)) label.grid(padx=5, pady=5) # internal padding in pixels root.mainloop() # run the tkinter event loop
# grid3.py import tkinter as tk root = tk.Tk() root.columnconfigure(0, minsize=100) # cell width root.rowconfigure(0, minsize=100) # row 0 root.rowconfigure(1, minsize=100) # row 1 label1 = tk.Label(root, text="A", bg="red") label1.grid(row=0, column=0, sticky=tk.NE) label2 = tk.Label(root, text="B", bg="blue") label2.grid(row=1, column=0, sticky=tk.SW) root.mainloop() # run the tkinter event loop
# grid4.py import tkinter as tk root = tk.Tk() root.rowconfigure(0, minsize=100) for i in range(4): root.columnconfigure(i, minsize=100) label1 = tk.Label(root, text="1", bg="black", fg="white") label2 = tk.Label(root, text="2", bg="black", fg="white") label3 = tk.Label(root, text="3", bg="black", fg="white") label4 = tk.Label(root, text="4", bg="black", fg="white") label1.grid(row=0, column=0) label2.grid(row=0, column=1, sticky=tk.EW) label3.grid(row=0, column=2, sticky=tk.NS) label4.grid(row=0, column=3, sticky=tk.NSEW) root.mainloop() # run the tkinter event loop