Why can't I define (and save) Tkinter fonts inside a function?

The definition of the font inside the function and in the main part of the script seems to behave differently, and I can’t understand how it should work.

For example, Labelthis example ends with a larger font, as expected:

from Tkinter import *
from ttk import *

import tkFont

root = Tk()

default = tkFont.Font(root=root, name="TkTextFont", exists=True)
large = default.copy()
large.config(size=36)

style = Style(root)
style.configure("Large.TLabel", font=large)

root.title("Font Test")

main_frame = Frame(root)
Label(main_frame, text="Large Font", style="Large.TLabel").pack()

main_frame.pack()
root.mainloop()

Screenshot of working version

However, if I try to define styles within the function, it seems that the font is being deleted or garbage is being collected and is inaccessible by the time the widget should use it:

from Tkinter import *
from ttk import *

import tkFont

def define_styles(root):
    default = tkFont.Font(root=root, name="TkTextFont", exists=True)

    large = default.copy()
    large.config(size=36)

    style = Style(root)
    style.configure("Large.TLabel", font=large)


root = Tk()

root.title("Font Test")

define_styles(root)

main_frame = Frame(root)
Label(main_frame, text="Large Font", style="Large.TLabel").grid(row=0, column=0)

main_frame.pack()
root.mainloop()

Screenshot of non-working version

A print tkFont.names()in the first version immediately before main_frame.pack()lists the custom font as font<id>, but when printing in the second version, the custom font is not displayed outside the function define_styles. Do I have to do something special to save them?

? - , ? tkFont , - , ?

+4
1

, , , large Font , Python define_styles. , Python , Tcl . , Tkinter PhotoImage.

, , . root, .

def define_styles(root):
    default = tkFont.Font(root=root, name="TkTextFont", exists=True)

    large = default.copy()
    large.config(size=36)

    style = Style(root)
    style.configure("Large.TLabel", font=large)
    root.myfont = large

:

enter image description here

+6

All Articles