基本設置按鈕如下:
import tkinter as tk
root = tk.Tk()
btn = tk.Button(root, text='顯示按鈕').pack()
root.mainloop()
修改按鈕點擊後的顏色:
btn = tk.Button(root, text='顯示按鈕', activebackground='red').pack()
修改按鈕點擊後的文字顏色:
btn = tk.Button(root, text='顯示按鈕', activebackground='red', activeforeground='white')
按鈕狀態設置:
import tkinter as tk
root = tk.Tk()
btn = tk.Button(root, text='正常按鈕', state=tk.NORMAL).pack()
btn2 = tk.Button(root, text='關閉按鈕', state=tk.DISABLED).pack()
btn3 = tk.Button(root, text='啟動按鈕', state=tk.ACTIVE).pack()
root.mainloop()
基本結構:
btn = Button( master, option=value, ... )
tkinter提供Button共20個參數如下所示:
1. activebackground: 當鼠標點擊按鈕時, 按鈕的背景顏色設定
2. activeforeground: 當鼠標放上按鈕時, 按鈕的前景顏色設定
3. bd: 按鈕邊框大小, 默認為2px
4. bg: 按鈕背景顏色
5. command: 與按鈕關聯的founction, 當按鈕被點擊時, 將執行此founction
6. fg: 按鈕上的文字顏色
7. font: 文字字體
8. height: 按鈕的高度
9. highlightcolor: 設定高亮的顏色
10. image: 按鈕上要顯示的圖片
11. justify: 顯示多行文字時, 設置不同行之間對齊的方式, 有三種選項(LEFT, RIGHT, CENTER)
12. padx: 按鈕在x軸方向上的內邊距(padding), 是指按鈕的內容與按鈕邊緣的距離
13. pady: 按鈕在y軸方向上的內邊距(padding), 是指按鈕的內容與按鈕邊緣的距離
14. relief: 邊框樣式, 設置組件3D效果, 有5種模式: FLAT, SUNKEN, RAISED, GROOVE, RIDGE, 默認為FLAT
15. state: 設定按鈕目前狀態, 有3種模式:NORMAL, ACTIVE, DISABLED,默認為NORMAL
16. underline: 下滑線,按鈕上的文字默認設定都不帶下滑線。 ex: 取值就是帶下滑線的字串索引, 為0時, 第一個字串帶下滑線, 為1時, 前兩個字串帶下滑線, 以此類推
17. width: 按鈕的寬度
18. wraplength: 限制按鈕每行顯示的文字數量
19. text: 按鈕的文字內容
20. anchor: 錨, 控制文字的位置, 默認為中心
Button提供2個呼叫函式(方法)如下所示:
1. flash(): Causes the button to flash several times between active and normal colors. Leaves the button in the state it was in originally. Ignored if the button is disabled.
2. invoke(): Calls the button's callback, and returns what that function returns. Has no effect if the button is disabled or there is no callback.
※查詢其他Tkinter GUI元件用法如下※