tkinter 字体在一个单独的文件中

tkinter font's in a seprate file

我有两个python文件,一个是带有字体信息的配置文件

这是我的配置文件:

from tkinter.font import Font

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

以下是我在主文件中遇到问题的行:

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()

最后,这是我希望解决的错误:

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

这是因为您在没有根目录的单独文件中定义字体 window。你可以通过将你的字体文件编辑为

来解决这个错误
# Your imports here
from tkinter import Tk
_root = Tk()

# rest of code here

这个问题可能是因为渲染字体需要初始化 window 因为在我使用过的几乎每个库中,它都需要 OpenGL 上下文。您可能必须先像这样创建一个 window

from tkinter import *
window=Tk()

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

# place your font here

window.mainloop()

您应该在创建 window 之后将导入移动到