Home > Back-end >  Get style font (Ttk)
Get style font (Ttk)

Time:06-02

I'm trying to get the font name and underline setting from a style that I've set.

The issue is, when I use:

style.lookup("My.TLabel", "font"),

it returns the string

font1

Why isn't style.lookup() returning the actual font name and the underline info?

import tkinter as tk
import tkinter.font as tkFont
from tkinter import ttk


root = tk.Tk()

custom_font = tkFont.Font(family="TkDefaultFont",
                          size=25,
                          underline=True)

style = ttk.Style()
style.configure("My.TLabel", font=custom_font)

info = style.lookup("My.TLabel", "font")
print(info) # <--Here, it gives me 'font1' instead of tkDefaultFont

root.mainloop()

Note: if I specify the font as a string, style.lookup() will work as expected:

style.configure("My.TLabel", font="TkDefaultFont 25 underline")
style.lookup("My.TLabel", "font")
>> TkDefaultFont 25 underline

But it won't return the font name using style.lookup() if I do this:

custom_font = tkFont.Font(family="TkDefaultFont",
                          size=25,
                          underline=True)
style.configure("My.TLabel", font=custom_font)
style.lookup("My.TLabel", "font")
>> font1

But I want to pass in a font object to style.configure() instead of a string. Any ideas on how to get style.lookup() to return the font name and underline setting?

CodePudding user response:

It turns out that a font object has a name field (string).

We can compare the font object's name with what style.lookup() will return. If they match, then we know we have the font that we're interested in. Then we can get the individual attributes (font name, size, underline) from the font object, using the cget() method.

Here's an example:

import tkinter as tk
import tkinter.font as tkFont
from tkinter import ttk


root = tk.Tk()

custom_font = tkFont.Font(family="TkDefaultFont",
                          size=25,
                          underline=True)

style = ttk.Style()
style.configure("My.TLabel", font=custom_font)

label_font = style.lookup("My.TLabel", "font")

if label_font == custom_font.name:
    # Get the font info
    font_name = custom_font.cget("family")
    size = custom_font.cget("size")
    is_underlined = custom_font.cget("underline")

    print(f"{font_name=}, {size=}, {is_underlined=}")


root.mainloop()

CodePudding user response:

The underlying tcl/tk engine has no knowledge of python objects so all it can do is return strings (and lists of strings).

The font module comes with a way to convert a font name into a font object. The following example illustrates how:

import tkinter as tk
import tkinter.font
from tkinter import ttk

style = ttk.Style()
font_name = style.lookup("My.TLabel", "font")
font = tkinter.font.nametofont(font_name)
print(f"family: {font.cget('family')} size: {font.cget('size')}")
  • Related