---
# System prepended metadata

title: grid( )方法
tags: [活用tkinter – 學習運用GUI]

---

# grid( )方法
###### tags: `活用tkinter – 學習運用GUI`




## row / colimn 
```python=
# label_3 = Label(root, text = "漂亮的女人都愛騙人", bg = "lightblue")

label_1.grid(row = 0, column = 0)
label_2.grid(row = 1, column = 0)
label_3.grid(row = 1, column = 1)
```
* 結果
![](https://i.imgur.com/pVVY416.png)

## columnspan 參數(標籤占用)
```python=
#label_1 = Label(root, text = "男人的嘴", bg = "lightgreen")
#label_2 = Label(root, text = "騙人的鬼", bg = "lightyellow")
#label_3 = Label(root, text = "漂亮的女人都愛騙人", bg = "lightblue")
label_4 = Label(root, text = "所以妳們都很醜", bg = "lightyellow")

label_1.grid(row = 0, column = 0)
label_2.grid(row = 0, column = 1)
label_3.grid(row = 1, column = 0, columnspan = 3)
label_4.grid(row = 1, column = 1)
```
* 結果
![](https://i.imgur.com/feNfMon.png)
* 總的來說，就是直接占空間，如果沒有設定好就會如上圖，被下一個設定值壓過去

## rowspan 參數
```python=
label_3.grid(row = 1, column = 0, rowspan = 6) 
```
* 結果
![](https://i.imgur.com/yOtyW2l.png)



## padx / pady 參數
```python=
label_3.grid(row = 1, column = 0, padx = 5) 
label_4.grid(row = 1, column = 1, padx = 5, pady = 10)
```
* 結果
![](https://i.imgur.com/LDIdhp5.png)

## sticky參數(類似anchor參數)
```python=
label_1.grid(row = 0, column = 0, padx = 10, sticky = W)
label_2.grid(row = 0, column = 1, sticky = W)
label_3.grid(row = 1, column = 0) 
label_4.grid(row = 1, column = 1, padx = 5, pady = 10)
# 嘗試把sticky參數拿掉，就樣就可以看到變化
```
* 結果
![](https://i.imgur.com/IeBTOfK.png)

## grid( )應用
```python=
from tkinter import *


root = Tk()
root.title("python-tkinter")
root.geometry("300x400")

colors = ["red", "green", "yellow", "pink", "blue", "black"]
r = 0
for color in colors:
    Label(root, text = color, relief = "groove", width = 20).grid(row = r, column = 0)
    Label(root, bg = color, relief = "ridge", width = 20).grid(row = r, column = 1)
    r += 1
    
root.mainloop()
```
## 調色盤
![](https://i.imgur.com/iaMHRV4.png)

* 使用rowconfigure / columnconfigure
```python=
# rowconfigure(0, weight = 1) row 0 的控件當視窗改變大小的縮放比是 1
# columnconfigure(0, weight = 1) column 0....(同上)

root.rowconfigure(1, weight = 1)
root.columnconfigure(0, weight = 1)

label_1.grid(row = 0, column = 0, padx = 5, pady = 5, sticky = W)
label_2.grid(row = 0, column = 1, padx = 5, pady = 5)
label_3.grid(row = 1, column = 0, columnspan = 2, padx = 5, pady = 5, sticky = N+W+S+E) 
```

* 結果(可以縮放試試看)
![](https://i.imgur.com/3Rut52V.png)





{%hackmd S1DMFioCO %}