Search code examples
python-3.xtkinterfontsttk

Multiple variations of TKInter fonts


I am trying to get a better understanding of using fonts in tkinter and ttk.

My plan is to have two different styles for headings, each with their own font size. I used nametofont() to create an instance of the font and then set the size in two different styles:

labelFont = tkinter.font.nametofont('TkTextFont')
labelFont.config(weight='bold')

ttk.Style().configure("TLabel", font=labelFont, size=12)
ttk.Style().configure("heading.TLabel", font=labelFont, size=48)

then apply the styles to headings:

heading = ttk.Label(root, text="Heading", style="heading.TLabel")
label = ttk.Label(root, text="Label", style="TLabel")   #   is style redundant?

Unfortunately, I don’t get two different sizes, so this is obviously the wrong approach.

I also tried something like this:

labelFont = tkinter.font.nametofont('TkTextFont')
headingFont = tkinter.font.nametofont('TkTextFont')
# etc

thinking that I would get two independent instance of the font, but they appear to be the same instance. If they were independent, I could have used configure() to give each of them their own font size.

I took this approach because I wanted to use the built-in named font, and use variables to maintain consistency. What is the correct approach to this?


Solution

  • You need to use .config(size=...) on the different instances of Font:

    labelFont = tkinter.font.nametofont('TkTextFont')
    labelFont.config(weight='bold', size=12)
    
    # create a clone of labelFont using Font.copy()
    headingFont = labelFont.copy()
    headingFont.config(size=48)
    
    s = ttk.Style()
    s.configure('TLabel', font=labelFont) # apply to all instance of ttk.Label
    s.configure('heading.TLabel', font=headingFont, size=96)
    
    heading = ttk.Label(root, text='Heading', style='heading.TLabel')
    label = ttk.Label(root, text='Label') # style='TLabel' is not necessary