GUI Python with Tkinter – Part 7 – Styling

In Tkinter you can specify how your widgets look like (color, font size, border etc).
The styling options are specified as options to the widgets either at the time of creating the widgets, or later by using the configure() option.
Now, let’s see how we can apply different colors, fonts, border widths, reliefs, cursors, and bitmap icons to widgets.

When styling the colors you can specify are the background color and the foreground color.
When styling text you can specify the fontfamily (written in lowercase), the fontsize (in pt or px), and the fontstyle (it can be normal / bold / italic and underline / overstrike).

You can change the border width of the widgets (default is 2 px usually) by specifying it explicitly borderwidth = 5.
The relief style of a widget refers to the difference between the highest and lowest elevations in a widget. There are six possible relief styles in Tkinter: flat, raised, sunken, groove, solid, and ridge (relief = 'raised').
You can change the style of the mouse cursor when you hover over a widget (cursor = 'cross').

Tkinter also offers a way to separate presentation from logic and specify styles in an external file (much like an external CSS), a text file where you can specify the common styling options. It is called external option database.


*background: Red
*Text*background: #000000
*Button*foreground: black
*Button*relief: raised
*Button*width: 5

The asterisk (*) means that the style is applied to all the instances of the given widget. These entries are placed in an external text file with the extension .txt. You have to call the file in your code by using the option_readfile() in your code:



from tkinter import *
root = Tk()

# connecting to the external styling optionstyle.txt

frame = Frame(root)

# placing widgets top-down
button1 = Button(frame, text = 'Motorcycles')
button1.pack(fill = X)
button2 = Button(frame, text = 'Power of the road')
button2.pack(fill = X)
button3 = Button(frame, text = 'CATCH ME IF U CAN')
button3.pack(fill = X)

# placing widgets side by side
button4 = Button(frame, text = 'Honda', font = 'Times 8')
button4.pack(side = LEFT)
button5 = Button(frame, text = 'Yamaha', font='Helvetica 24 bold italic')
button5.pack(side = LEFT)
button6 = Button(frame, text = 'Suzuki')
button6.pack(side = LEFT)

# Individual styling with configure()
button1.configure(borderwidth = 7)
button2.configure(cursor = 'cross')


Here is what you get if you run the file in the terminal:

Styling in Tkinter

Leave a Reply