My task is to create a label and button on Tkinter. The button has to change the label, and I have to change the colour of the button and the label. I have changed the colour of
On Windows 10, I have run into the same problem, and have found a solution, although not a very satisfying one. The following will create a black button with white foreground type:
First define a custom button style based on the standard TButton style
mystyle = ttk.Style()
mystyle.configure('mycustom.TButton',background='black',foreground='white')
Then create the button using the new custom style
mybutton = ttk.Button(root,style='mycustom.Tbutton')
I say 'not very satisfying' because this only works if I have previously set the overall theme to 'default' as follows:
mystyle = ttk.Style()
mystyle.theme_use('default')
Using any of the other themes available on my system (winnative,clam,alt,classic,vista and xpnative) will change only the border to black, and leave the background grey.
From
Python, Tkinter, Change of label color
This will change the label color of a button:
button1.configure(foreground="red")
I assume the same approach can be used for the label.
For a ttk button the primary issue with color control requires usage of ttk.Style() and theme_use. Themes alt/classic/default allow 3D/color button control. See Python: Changing ttk button color depending on current color? for a code example using configure and map for style.
So configuring a buttons colors is a bit different when using tkinter
button VS a ttk
style button.
For a tkinter button you would use the background = "color" argument like the following:
button1 = Button( rootWindow, text="Change Label",
background = 'black', foreground = "white", command=change)
For a ttk
button you would configure the style and then use the style = "style name"
argument like the following.
style = ttk.Style()
style.configure("BW.TLabel", foreground="white", background="black")
buttonTTK = ttk.Button( rootWindow, text="TTK BUTTON",style = "BW.TLabel", command=change)
More information on ttk
configs can be found here
from tkinter import *
from tkinter import ttk
def change():
print("change functon called")
def main():
rootWindow = Tk()
label = ttk.Label( rootWindow, text="Hello World!",
background = 'black', foreground = "white")
label.pack()
button1 = Button( rootWindow, text="Change Label",
background = 'black', foreground = "white", command=change)
button1.pack()
style = ttk.Style()
style.configure("BW.TLabel", foreground="white", background="black")
buttonTTK = ttk.Button( rootWindow, text="TTK BUTTON",style = "BW.TLabel", command=change)
buttonTTK.pack()
rootWindow.mainloop()
main()
Result: