首页 > 解决方案 > 有没有办法改变python中ttk按钮的背景颜色?我尝试使用样式方法,但它只是改变了边框颜色

问题描述

from tkinter import *

from tkinter.ttk import *

from tkinter import ttk

root = Tk()

stl = ttk.Style()

stl.map('C.TButton',
     foreground = [('pressed','red'),('active','blue')],
     background = [('pressed','!disabled','black'),('active','white')]
)
#background not changing.It is still grey

ttk.Button(root, text='This is a button', style='C.TButton').pack()

root.mainloop()

我尝试使用样式类并在 C.TButton 中进行了一些更改,但似乎只是更改了边框颜色而不是更改按钮的颜色。按钮仍然是灰色和扁平的帮助!

标签: buttontkinterpython-3.7ttk

解决方案


我也遇到了同样的问题。您可以使用 TLabel 而不是 TButton 来更改预期的背景颜色。但是,按钮级文本周围没有填充空间。您需要使用 configure 方法指定填充。如果指定 TLabel,Style 作为按钮好像丢失了,还需要指定浮雕。

from tkinter import *

from tkinter.ttk import *

from tkinter import ttk

root = Tk()

stl = ttk.Style()
root.geometry('800x600')

stl = ttk.Style()
stl.configure('C.TLabel',padding=[30,10,50,60])

stl.map('C.TLabel',
    foreground = [('pressed','red'),('active','blue')],
    background = [('pressed','!disabled','black'),('active','white')],
    relief=[('pressed', 'sunken'),
            ('!pressed', 'raised')]
)

ttk.Button(root, text='This is a button', style='C.TLabel').pack()

root.mainloop()


推荐阅读