Styling a tk widget

In order to style a tk widget, we simply use keyword arguments upon its creation, or the configure method if we wish to alter it afterwards.

Let's open up another Python file and have a go at styling some tk widgets:

import itertools
import tkinter as tk

style_1 = {'fg': 'red', 'bg': 'black', 'activebackground': 'gold', 'activeforeground': 'dim gray'}
style_2 = {'fg': 'yellow', 'bg': 'grey', 'activebackground': 'chocolate', 'activeforeground': 'blue4'}
style_cycle = itertools.cycle([style_1, style_2])

def switch_style():
style = next(style_cycle)
button.configure(**style)

win = tk.Tk()

button = tk.Button(win, text="style switch", command=switch_style)
button.pack(padx=50, pady=50)

win.mainloop()

In this file, we begin by creating two dictionaries full of keyword-argument to value mappings. The dictionary keys (fg, bg, and so on) are arguments which can be passed when initializing a widget, or to the configure method, to change its styling. The values of the dictionary are color names which will be assigned to these attributes.

The attributes we will be changing are:

  • fg: The button's foreground (text) color
  • bg: The button's background color
  • activebackground: The button's background color when pressed
  • activeforeground: The button's foreground (text) color when pressed

These two dictionaries are put into a list and passed to the cycle function from the itertools module. This function simply takes an iterable and returns each value when next is called on it. Once it reaches the end of the iterable, it then continues from the beginning, thus creating a cycle.

A function is then created named switch_style. This function will call next on our cycle and pass the arguments from the dictionary to the button's configure method. This will call the method and update the styling of our button.

The last four lines should look familiar. A main window is created with the Tk widget, a Button widget is created and bound to our switch_style function, the button is packed, and the window is displayed with mainloop.

Run this code and give the button a few clicks. Hold the mouse down on it and note the color change when the button is active which is shown in the following screenshot:

This is styling tk widgets in a nutshell. While I haven't covered every possible aspect of a widget that can be styled, the method of doing so will be the same.

A list of aspects and values can be found online. One possible source is
http://effbot.org/tkinterbook/tkinter-widget-styling.htm.

Styling a ttk widget is quite different. These require a special Style object to be created for each widget type. Let's have a go at styling some ttk widgets.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset