การเปลี่ยน/รีเซ็ตสีพื้นหลัง (Background) และสีข้อความ (Foreground) ของปุ่ม Tkinter ทำได้ด้วย btn.configure(bg="color", fg="color") หรือ btn.config(...)
ตัวอย่างโค้ด
from tkinter import *
from tkinter import ttk
win = Tk()
win.geometry("750x250")
def change_color():
btn.configure(bg="OrangeRed3", fg="white")
Label(win, text="Click the Button to reset the Color of the Button",
font=('Georgia 16 italic')).pack(pady=30)
btn = Button(win, text="RESET", command=change_color, font=('Georgia 11'))
btn.pack(side=TOP, ipady=5, ipadx=20)
win.mainloop()
สีที่ใช้ได้ใน Tkinter
- ชื่อสีมาตรฐาน:
'red','blue','green','yellow','white','black','gray','OrangeRed3' - Hex:
'#FF0000','#00FF00','#RRGGBB' - RGB Tuple: ไม่รองรับโดยตรง ต้องแปลงเป็น Hex
สำหรับ ttk.Button (Themed)
ttk.Button ไม่รองรับ bg/fg โดยตรง ต้องใช้ ttk.Style:
style = ttk.Style()
style.configure('Red.TButton', background='red', foreground='white')
style.map('Red.TButton',
background=[('active', 'darkred'), ('pressed', 'maroon')])
btn = ttk.Button(win, text="Styled", style='Red.TButton')
การ Reset กลับสู่ Default
# Classic Button
btn.configure(bg='SystemButtonFace', fg='SystemButtonText') # Windows Default
# ttk Button
btn.configure(style='TButton') # กลับสู่ Default Style
การเปลี่ยนสีแบบ Dynamic (Hover Effect)
def on_enter(e):
e.widget.configure(bg='lightblue')
def on_leave(e):
e.widget.configure(bg='SystemButtonFace')
btn.bind('', on_enter)
btn.bind('', on_leave)
การประยุกต์ใช้
Status Indicator (Red/Green), Warning Buttons, Theme Toggle, Highlight Active Tool, Form Validation Feedback