如何更改 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