Notebook 基本概念
Notebook 是一個Widget 容器控件,這個控件的特點就是有許多選項卡,當選擇不同選項卡時可以看到不同的子控件內容,也可以當做子窗口內容,Notebook 是屬於tkinter.ttk
模塊的控件
構造方法如下:
Notebook(父對象, options)
參數:
- 第一個參數:
父對象
,表示這個選項卡將建立在哪一個窗口內 - 第二個參數:
options
,參數如下
參數 | 含義 |
---|---|
height | 如果設置數值則使用設置高度 默認是使用最大可能 高度 |
padding | 設置Notebook外圍的額外空間 ,可以設置4個數值代表left、top、tight、bottom四周的空間 |
width | 如果設置數值則使用設置寬度 默認是使用最大可能 寬度 |
整個建立Notebook框架的步驟:
- Notebook()建立Notebook對象,假設對象名稱是notebook
- 使用notebook對象調用add()方法
add(子對象, text='xxx')
- xxx是要添加的選項卡名稱
- 上述代碼可以將子對象插入notebook,同時產生’xxx’選項卡名稱
如果用正規語法表示add()
方法,它的語法格式如下
add(子對象, options)
options參數如下:
參數 | 含義 |
---|---|
compound | 可以設置當選項卡內同時含圖像和文字時,彼此之間的位置關係 |
image | 選項卡以圖像 方式呈現 |
padding | 設置Notebook和麪板Pane的額外空間 |
state | 可能值是normal、disabled、hidden 如果是 disabled 表示無法被選取使用如果是 hidden 表示被隱藏 |
sticky | 指出子窗口面板的配置方式,n/s/e/w 分別表示North、South、East、West |
text | 選項卡中的字符串內容 |
underline | 指出第幾個字母含下劃線 從0開始計算的索引 |
Notebook 基本應用
例子
:
import tkinter
import tkinter.ttk
root = tkinter.Tk()
root.geometry('300x180')
notebook = tkinter.ttk.Notebook(root)
frameOne = tkinter.Frame()
frameTwo = tkinter.Frame()
notebook.add(frameOne, text='選項卡1')
notebook.add(frameTwo, text='選項卡2')
notebook.pack(padx=10, pady=5, fill=tkinter.BOTH, expand=True)
root.mainloop()
運行結果:
綁定選項卡與子控件內容
例子
:
import tkinter
import tkinter.ttk
root = tkinter.Tk()
root.geometry('150x120')
def show():
labelOther.config(text='Tkinter')
labelOther.config(bg='lightgreen')
notebook = tkinter.ttk.Notebook(root)
frameOne = tkinter.Frame()
frameTwo = tkinter.Frame()
# 添加內容
label = tkinter.Label(frameOne, text='Python', bg='lightblue', fg='red')
label.pack(padx=10, pady=5)
button = tkinter.Button(frameTwo, text='請點擊', command=show)
button.pack(padx=10, pady=5)
labelOther = tkinter.Label(frameTwo, fg='red')
labelOther.pack(padx=10, pady=5)
notebook.add(frameOne, text='選項卡1')
notebook.add(frameTwo, text='選項卡2')
notebook.pack(padx=10, pady=5, fill=tkinter.BOTH, expand=True)
root.mainloop()
運行結果:
謝謝觀看,筆者會持續更新,如有錯誤或者建議,請私信我