Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the color of ttk button

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:

enter image description here

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:

enter image description here

Kindly help me achieve my desired button.

like image 366
maq Avatar asked Dec 07 '14 21:12

maq


People also ask

How do I add color to my TTK button?

Build A Paint Program With TKinter and Python Ttk works like CSS in an HTML script. It has many inbuilt functions, modules and methods that add style to a regular tkinter widget. Tkinter ttk buttons generally have a default color scheme, thus we can change the background color of these buttons by configuration method.

How do I style a TTK widget?

Generally, the style name of a ttk widget starts with the letter 'T' followed by the widget name, for example, TLabel and TButton . In Tkinter, every widget has a default widget class. A widget class defines the default style for a widget. Horizontal.


1 Answers

Although it is not as simple as with Tk buttons, it is possible. In ttk, if you set the theme_use attribute to any of these: ('winnative', 'clam', 'alt', 'default', 'classic', 'vista', 'xpnative'), you should be able to modify the default behaviour. I set the "style.map" attribute to avoid background colour change due to mouse hover (The state of the button is always 'active').

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

Hope this helps.

like image 193
Ujjwal Mohanty Avatar answered Sep 20 '22 16:09

Ujjwal Mohanty