Tkinter (02) 按鈕部件 Button

Jason990420發表於2020-07-12

按鈕部件的建立及其選項

w = tk.Button(parent, option=value, ...)
activebackground 滑鼠懸停在按鈕上時顯示的背景顏色
activeforeground 滑鼠懸停在按鈕上時顯示的前景顏色
anchor 文字定位
bd or borderwidth 邊框寬度
bg or background 正常背景色
bitmap 用來替代文字的標準點陣圖名
command 點選時呼叫的函式
cursor 滑鼠懸停在按鈕上時顯示的游標
default tk.NORMAL 或 tk.DISABLED 的按鈕
disabledforeground 禁用時的前景顏色
fg or foreground 正常前景色
font 文字字型
height 按鈕的高度, 文字行數或影像畫素數
higtlightbackground 非焦點時高亮顏色
highlightcolor 焦點時高亮顏色
highlightthickness 聚焦高亮厚度
image 按鈕上的影像
justify 多行對齊, tk.LEFT, tk.RIGHT 及 tk.CENTER
overrelief 滑鼠懸停按鈕時的浮雕樣式, 預設為 tk.RAISED
padx 在文字左側和右側填充間隔
pady 在文字上方和下方填充間隔
relief 浮雕樣式, 預設為 tk.RAISED
repeatdelay 直到經過指定時間(毫秒), 開始重複按下按鈕
repeatinterval 重複間隔, 以毫秒為單位重複按下按鈕
state tk.NORMAL, tk.ACTIVE (滑鼠懸停在其上) 以及 tk.DISABLED
takefocus 鍵盤聚焦, 0 或 1
text 按鈕文字
textvariable StringVar(), 更改變數將更新按鈕上的文字
underline 下劃線的索引處,無則為 -1
width 按鈕寬度, 文字行數或影像畫素數
wraplength 將文字以其適合的長度換行

按鈕部件的方法

flash() 按鈕在滑鼠懸停時的顏色和常規顏色之間閃爍切換
invoke() 單擊按鈕,返回回撥的返回值

一般的使用方式

  1. 匯入 tkinter
  2. 定義 Button 的回撥函式
  3. 建立主要視窗, 以作為其他部件的容器
  4. 建立部件, 如 Button
  5. 加入部件到佈局中
  6. 開始主要視窗的 mainloop()

範例視窗及程式碼

nCY2s0psdQ.png!large

from tkinter import *
from functools import partial # For callback with arguments

# Callback for Buttons
def callback(bttn):
    label.configure(text=f'{bttn} clicked !')

# Constructor for Buttons
def button(text, size, color):
    bttn = Button(root, text=text, **size, **color, command=partial(callback, text))
    return bttn

# main window as container of widgets
root  = Tk(className='Button')

# Color theme
white = {'bg':'white', 'fg':'white'}
green = {'bg':'green', 'fg':'white'}
blue  = {'bg':'blue', 'fg':'white'}

# Create Buttons
button00 = button('Button00', {'width':20, 'height':2}, green)
button01 = button('Button01', {'width':10, 'height':1}, blue)
button10 = button('Button10', {'width':10, 'height':1}, blue)
button11 = button('Button11', {'width':10, 'height':1}, green)

# Create Label here to show which button clicked
blank = Label(root, text='', width=20, height=1, **white)
label = Label(root, text='', width=30, height=1, **green)

# Show Buttons & labels
button00.grid(row=0, column=0)
button01.grid(row=0, column=1, sticky=NSEW)
button10.grid(row=1, column=0, sticky=NSEW)
button11.grid(row=1, column=1)
blank.grid(row=2, column=0)
label.grid(row=3, column=0, columnspan=2)

# Tkinter loop for event and refresh
root.mainloop()
本作品採用《CC 協議》,轉載必須註明作者和本文連結

Jason Yang

相關文章