How to change the color of ttk button

不问归期 提交于 2019-11-30 03:09:26

问题


I am using Python 3.x on Windows.

My problem is I want to customize a button widget of ttk by completely changing its background and foreground color. But so far, I have been unsuccessful.

My desired button is:

I read the ttk.Style guide and used their code:

ttk.Style().configure("TButton", padding=6, relief="flat",
   background="#000")

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

But it's changing the border color instead of the whole button bakground. Here is the output:

Kindly help me achieve my desired button.


回答1:


Unfortunately, there isn't an easy way to change the foreground of a button from the ttk library. It is always the standard Windows gray like in your picture.

But you can easily get what you want with a normal tkinter.Button if you set the right options. Below is an example script:

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()

And here is what it will look like:

Also, the shade of green I picked was just an example one that I thought was pretty close to what you wanted. But you can specify any hex color code you want. If you need to turn a RGB value into hex, a simple trick is to use str.format like so:

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



回答2:


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.")

works for me if you want to change all your buttons to the one you "desire", with Python 2.7 and Tkinter 8.6



来源:https://stackoverflow.com/questions/27347981/how-to-change-the-color-of-ttk-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!