Button小部件是一個標准的Tkinter的部件,用於實現各種按鈕。按鈕可以包含文本或圖像,您可以調用Python函數或方法用於每個按鈕。 Tkinter的按鈕被按下時,會自動調用該函數或方法。
該按鈕可以只顯示在一個單一的字體的文本,但文本可能跨越一個以上的行。此外,一個字符可以有下划線,例如標記的鍵盤快捷鍵。默認情況下,使用Tab鍵可以移動到一個按鈕部件。
通常使用工具欄按鈕,在應用程序窗口,並接受或解雇在對話框中輸入的數據。
Button按鈕屬性
| 函數 |
描述 |
| text |
顯示文本內容 |
| command |
指定Button的事件處理函數 |
| compound |
指定文本與圖像的位置關系 |
| bitmap |
指定位圖 |
| focus_set |
設置當前組件得到的焦點 |
| master |
代表了父窗口 |
| bg |
設置背景顏色 |
| fg |
設置前景顏色 |
| font |
設置字體大小 |
| height |
設置顯示高度、如果未設置此項,其大小以適應內容標簽 |
| relief |
指定外觀裝飾邊界附近的標簽,默認是平的,可以設置的參數; flat、groove、raised、ridge、solid、sunken |
| width |
設置顯示寬度,如果未設置此項,其大小以適應內容標簽 |
| wraplength |
將此選項設置為所需的數量限制每行的字符,數默認為0 |
| state |
設置組件狀態;正常(normal),激活(active),禁用(disabled) |
| anchor |
設置Button文本在控件上的顯示位置 可用值:n(north),s(south),w(west),e(east),和ne,nw,se,sw |
| bd |
設置Button的邊框大小;bd(bordwidth)缺省為1或2個像素 |
| textvariable |
設置Button與textvariable屬性 |
Button按鈕方法
以下是Button常用的小工具
| 方法 |
描述 |
| flash() |
Flash the button. This method redraws the button several times, alternating between active and normal appearance. |
| invoke() |
Invoke the command associated with the button. |
Python Tkinter Button示例代碼
創建了4個Button按鈕、設置了不同的屬性
width,height,relief,bg,bd,fg,state,bitmap,command,anchor
from tkinter import * from tkinter import messagebox root = Tk() root.title("Button Test") def callback(): messagebox.showinfo("Python command","人生苦短、我用Python") """ 創建4個Button按鈕、並設置width,height,relief,bg,bd,fg,state,bitmap,command,anchor """ Button(root, text="外觀裝飾邊界附近的標簽", width=21,height=3,relief=RAISED).pack() Button(root, text="設置按鈕狀態",width=21,state=DISABLED).pack() Button(root, text="設置bitmap放到按鈕左邊位置", compound="left",bitmap="error").pack() Button(root, text="設置command事件調用命令", fg="blue",bd=7,width=28,command=callback).pack() Button(root, text ="設置高度寬度以及文字顯示位置",anchor = 'sw',width = 30,height = 2).pack() root.mainloop()
