关于python:如何更改ttk按钮的颜色

How to change the color of ttk button

我在Windows上使用Python3.x。

我的问题是我想通过完全更改其背景和前景色来自定义ttk的按钮小部件。 但是到目前为止,我一直没有成功。

我想要的按钮是:

enter image description here

我阅读了ttk.Style指南并使用了它们的代码:

1
2
3
4
5
ttk.Style().configure("TButton", padding=6, relief="flat",
   background="#000")

btn = ttk.Button(text="Sample")
btn.pack()

但是它改变了边框的颜色,而不是整个按钮的背景。 这是输出:

enter image description here

请帮助我实现所需的按钮。


不幸的是,没有一种简单的方法可以从ttk库中更改按钮的前景。就像您的图片一样,它始终是标准的Windows灰色。

但是,如果设置正确的选项,您可以使用普通的tkinter.Button轻松获得所需的内容。下面是一个示例脚本:

1
2
3
4
5
6
7
8
9
10
11
12
import tkinter as tk

root = tk.Tk()
btn = tk.Button(root,
                bg='#000000',
                fg='#b7f731',
                relief='flat',
                text='hello button',
                width=20)
btn.pack()

root.mainloop()

这是它的样子:

enter image description here

另外,我选择的绿色只是我认为非常接近您想要的一个示例。但是您可以指定所需的任何十六进制颜色代码。如果需要将RGB值转换为十六进制,一个简单的技巧就是使用str.format,如下所示:

1
2
3
4
>>> rgb = (183, 247, 49)
>>> '#{:02x}{:02x}{:02x}'.format(*rgb)
'#b7f731'
>>>


尽管它不像Tk按钮那样简单,但它是可能的。在ttk中,如果将theme_use属性设置为以下任意一项:(" winnative"," clam"," alt"," default"," classic"," vista"," xpnative"),则应该可以进行修改默认行为。我设置了" style.map"属性,以避免由于鼠标悬停而导致背景颜色变化(按钮的状态始终为"活动")。

1
2
3
4
5
6
7
8
9
10
11
12
import tkinter as tk
from tkinter import ttk

style = ttk.Style()
style.theme_use('alt')
style.configure('TButton', background = 'red', foreground = 'white', width = 20, borderwidth=1, focusthickness=3, focuscolor='none')
style.map('TButton', background=[('active','red')])

root = tk.Tk()
button = ttk.Button(root,text='Quit')
button.place(relx=0.3,rely=0.4)  
root.mainloop()

希望这可以帮助。


1
2
3
4
5
6
7
import ttk

root.style = ttk.Style()
#root.style.theme_use("clam")
style.configure('TButton', background='black')
style.configure('TButton', foreground='green')
button= ttk.Button(self, text="My background is black and my foreground is green.")

如果您想使用Python 2.7和Tkinter 8.6将所有按钮更改为您想要的按钮,则对我有用