How to change a widget’s font style without knowing the widget’s font family/size?

There’s a much better way than using .config() to change your application font, especially if your goal is to change the font for a whole group of widgets or all widgets.

One of the really great features of Tk is the notion of “named fonts”, which are implemented as objects in tkinter. The beauty of named fonts is, if you update the font, all widgets that use that font will automatically get updated. So, configure your widgets once to use a font object, then you can update all widgets at once simply by changing the configuration of the font object.

Here’s a quick example:

import tkinter as tk
import tkinter.font


class App:
    def __init__(self):
        root=tk.Tk()
        # create a custom font
        self.customFont = tkinter.font.Font(family="Helvetica", size=12)

        # create a couple widgets that use that font
        buttonframe = tk.Frame()
        label = tk.Label(root, text="Hello, world", font=self.customFont)
        text = tk.Text(root, width=20, height=2, font=self.customFont)

        buttonframe.pack(side="top", fill="x")
        label.pack(side="top", fill="x")
        text.pack(side="top", fill="both", expand=True)
        text.insert("end","press +/- buttons to change\nfont size")

        # create buttons to adjust the font
        increase_font = tk.Button(root, text="+", command=self.increase_font)
        decrease_font = tk.Button(root, text="-", command=self.decrease_font)

        increase_font.pack(in_=buttonframe, side="left")
        decrease_font.pack(in_=buttonframe, side="left")

        root.mainloop()

    def increase_font(self):
        '''Make the font 2 points bigger'''
        size = self.customFont['size']
        self.customFont.configure(size=size+2)

    def decrease_font(self):
        '''Make the font 2 points smaller'''
        size = self.customFont['size']
        self.customFont.configure(size=size-2)

app=App()

If you don’t like that approach, or if you want to base your custom font on the default font, or if you’re just changing one or two fonts to denote state, you can use font.actual to get the actual size of a font for a given widget. For example:

import tkinter as tk
import tkinter.font

root = tk.Tk()
label = tk.Label(root, text="Hello, world")
font = tkinter.font.Font(font=label['font'])
print(font.actual())

When I run the above I get the following output:

{'family': 'Lucida Grande', 
 'weight': 'normal', 
 'slant': 'roman', 
 'overstrike': False, 
 'underline': False, 
 'size': 13}

Leave a Comment