How to change the color of ttk button

前端 未结 3 1857
长发绾君心
长发绾君心 2020-12-31 05:37

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.

相关标签:
3条回答
  • 2020-12-31 06:07

    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:

    enter image description here

    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'
    >>>
    
    0 讨论(0)
  • 2020-12-31 06:15
    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

    0 讨论(0)
  • 2020-12-31 06:33

    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.

    0 讨论(0)
提交回复
热议问题