Home > Software engineering >  tkinter font's in a seprate file
tkinter font's in a seprate file

Time:11-01

I have two python files, one is a config file with font information

Here is my config file:

from tkinter.font import Font

HEADER_FONT = Font(
  family="Futura",
  size=22,
  weight="bold",
)

Here are the lines I am having trouble within my main file:

import app.config.colors as colors
import app.config.fonts as fonts

root = tk.Tk()
headerFrame = tk.LabelFrame(root, bg=colors.WHITE, bd=0)
headerFrame.pack(side="top", fill="x")

headerLabel = tk.Label(headerFrame, text="job automator 2", fg=colors.PRIMARY, bg=colors.WHITE, font=fonts.HEADER_FONT).pack(padx=5, pady=10, anchor=W)

root.mainloop()

And finally, here is my error I wish to solve:

Traceback (most recent call last):
  File "c:\Users\Tommy's Gaming PC\Desktop\Python Projects\JobAutomator2\app.py", line 12, in <module>
    import app.config.fonts as fonts
  File "c:\Users\Tommy's Gaming PC\Desktop\Python Projects\JobAutomator2\app\config\fonts.py", line 11, in <module>
    HEADER_FONT = Font(
  File "C:\Users\Tommy's Gaming PC\AppData\Local\Programs\Python\Python39\lib\tkinter\font.py", line 72, in __init__
    root = tkinter._get_default_root('use font')
  File "C:\Users\Tommy's Gaming PC\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 297, in _get_default_root
    raise RuntimeError(f"Too early to {what}: no default root window")
RuntimeError: Too early to use font: no default root window

CodePudding user response:

This problem is probably because rendering a font requires an initialized window since on pretty much every library I've used, it requires OpenGL context. You probably have to create a window first like this

from tkinter import *
window=Tk()

window.title('Hello Python')
window.geometry("300x200 10 20")

# place your font here

window.mainloop()

You should move the imports to AFTER the window is created

CodePudding user response:

it's because you are defining fonts in seprate file having no root window. you can solve this error by editing your font carrying file as

# Your imports here
from tkinter import Tk
_root = Tk()

# rest of code here
  • Related