pythontkinter

How to get font family name using cget


I'm using the following code:

from tkinter import *
from tkinter.font import Font
root = Tk()
root.title("Font window")
root.geometry("500x500")

my_font = Font(
    family = 'Helvetica',
    size = 30,
    weight = 'bold',
    slant = 'roman',
    underline = 1,
    overstrike = 0
)
my_label = Label(root, text="Peter Pan", fg="Green", bg="White", font = my_font)

value = my_label.cget("text")
print(value)

my_label.pack()
root.mainloop()

This works, however how do I get the font family value or font size value?


Solution

  • You can use cget to get the string name of the font associated with the label. For example, when I run your code, print(my_label.cget("font")) will print "font1". To convert that to the font object you have to import nametofont from tkinter.font. With that, you can get information about the font.

    from tkinter.font import nametofont
    ...
    font_name = my_label.cget("font")
    font_object = nametofont(font_name)
    print(font_object.cget("family"), font_object.cget("size"))