如何在 tkinter 中使用自定义字体路径? Windows 仅

How to use custom font path in tkinter? Windows ONLY

我想使用与我的 python 程序在同一目录中的字体,但实际上 python 会在 windows 字体文件夹中搜索它,我应该如何修复它?

(我想给我的程序提供字体路径或导入字体以在我的标签中使用它)

例如: 这里,如果字体 myfont 位于字体文件夹中,我的程序将运行,但如果不是,它将以默认字体显示。

from tkinter import * root = Tk() my_lab = Label(root,font=("myfont" ,10 )).place(x=1,y=1)

我用过font=(f"path/to/font",10)但是没用

Question: How to use custom font path in tkinter? Windows ONLY

参考:

  • SO:Answer - Truly custom font in Tkinter

    def loadfont(fontpath, private=True, enumerable=False)


将函数更改为Python 3:

def loadfont(fontpath, private=True, enumerable=False):
    ...

    # For 3.x, you have to convert the isinstance checks to bytes and str

    if isinstance(fontpath, bytes):
        pathbuf = create_string_buffer(fontpath)
        AddFontResourceEx = windll.gdi32.AddFontResourceExA

    elif isinstance(fontpath, str):
        pathbuf = create_unicode_buffer(fontpath)
        AddFontResourceEx = windll.gdi32.AddFontResourceExW
    ...

尝试参数的变体 private=Falseenumerable=True 并确保您输入的字体名称正确。

运行函数loadfont(...),如:

loadfont("path//to//font.ttf", private=False, enumerable=True)