Welcome folks today in this blog post we will be applying custom css to tkinter widgets in window. All the full source code of the application is shown below.
Get Started
In order to get started you need to install the below library using the pip
command as shown below
pip install tkstylesheet
Now after installing this you nee to make an app.py
file and copy paste the below code
app.py
1 2 |
from tkinter import * from tkstylesheet import TkThemeLoader |
As you can see first of all we are importing the tkstylesheet
library from the tkthemeloader. And also we are importing all the methods from the tkinter.
Displaying the Widgets in Tkinter
1 2 3 4 5 6 |
root = Tk() Label(root, text="label").pack() Button(root, text="Button").pack() root.mainloop() |
As you can see we have the label and the button widgets of tkinter. And then we are adding this to window using the pack()
method. And now we need to apply some custom css to these widgets.
Applying Custom CSS to Widgets
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
_style = """ Tk{ background: "#fff"; /*background color of the root widget*/ } Label{ foreground: "#ebebeb"; background: "#565657"; } Button{ foreground: "#ebebeb"; background: "#565657"; } """ |
And now as you can see we have defined the above custom css which will be applied to all the widgets of the tkinter. As you can see all the properties of the CSS are supported. As you can see we are changing the background color of whole window to the hexadecimal color. And also we are targeting the buttons and the label widgets. All the basic CSS Selectors are also supported. Here above we have written the basic CSS that you know in web development.
Applying the Custom CSS to Tkinter Widgets
1 2 |
theme = TkThemeLoader(root) theme.setStylesheet(_style) # pass as string |
Full Source Code
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
from tkinter import * from tkstylesheet import TkThemeLoader _style = """ Tk{ background: "#fff"; /*background color of the root widget*/ } Label{ foreground: "#ebebeb"; background: "#565657"; } Button{ foreground: "#ebebeb"; background: "#565657"; } """ root = Tk() Label(root, text="label").pack() Button(root, text="Button").pack() theme = TkThemeLoader(root) theme.setStylesheet(_style) # pass as string root.mainloop() |