如何更改 Tkinter 按鈕顏色
Tkinter Button
控制元件具有屬性 bg
和 fg
來設定背景和前景色。我們可以在初始化 Button 物件時為 bg
和 fg
分配顏色,並使用 configure
方法更改 Tkinter Button 的顏色或為 bg
和 fg
鍵分配新值。
設定 Tkinter Button
顏色
import tkinter as tk
class Test():
def __init__(self):
self.root = tk.Tk()
self.root.geometry("250x100")
self.buttonA = tk.Button(self.root,
text = "Color",
bg = "blue",
fg = "red")
self.buttonB = tk.Button(self.root,
text="Click to change color",
bg = "gray",
fg = "purple")
self.buttonA.pack(side=tk.LEFT)
self.buttonB.pack(side=tk.RIGHT)
self.root.mainloop()
app=Test()
你也可以將 bg
替換為 background
,將 fg
替換為 foreground
來設定 Tkinter Button
背景和前景色。
import tkinter as tk
class Test():
def __init__(self):
self.root = tk.Tk()
self.root.geometry("250x100")
self.buttonA = tk.Button(self.root,
text = "Color",
background = "blue",
foreground = "red")
self.buttonB = tk.Button(self.root,
text="Click to change color",
background = "gray",
foreground = "purple")
self.buttonA.pack(side=tk.LEFT)
self.buttonB.pack(side=tk.RIGHT)
self.root.mainloop()
app=Test()
用 configure
方法改變 Tkinter Button
顏色
建立 Tkinter Button
控制元件之後,我們可以使用 configure
方法更改其顏色。
import tkinter as tk
class Test():
def __init__(self):
self.root = tk.Tk()
self.root.geometry("250x100")
self.buttonA = tk.Button(self.root,
text = "Color",
bg = "blue",
fg = "red")
self.buttonB = tk.Button(self.root,
text="Click to change color",
command=self.changeColor)
self.buttonA.pack(side=tk.LEFT)
self.buttonB.pack(side=tk.RIGHT)
self.root.mainloop()
def changeColor(self):
self.buttonA.configure(bg="yellow")
app=Test()
self.buttonA.configure(bg="yellow")
它將背景 bg
配置為黃色。
使用 bg
/fg
屬性更改 Tkinter Button
顏色
bg
和 fg
是 Tkinter Button 控制元件物件字典的鍵值,因此,我們可以通過為這些鍵指定新的值來更改 Tkinter Button 的顏色。
import tkinter as tk
class Test():
def __init__(self):
self.root = tk.Tk()
self.root.geometry("250x100")
self.buttonA = tk.Button(self.root,
text = "Color",
bg = "blue",
fg = "red")
self.buttonB = tk.Button(self.root,
text="Click to change color",
command=self.changeColor)
self.buttonA.pack(side=tk.LEFT)
self.buttonB.pack(side=tk.RIGHT)
self.root.mainloop()
def changeColor(self):
self.buttonA["bg"]="gray"
self.buttonA["fg"]="cyan"
app=Test()
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn