如何使用Python获取已安装的Windows字体列表?

问题描述 投票:0回答:4

如何获取计算机系统上所有字体名称的列表?

python operating-system os.path listdir
4个回答
6
投票

这只是列出

Windows\fonts
中的文件的问题:

import os

print(os.listdir(r'C:\Windows\fonts'))

输出是一个以如下内容开头的列表:

['arial.ttf', 'arialbd.ttf', 'arialbi.ttf', 'cambria.ttc', 'cambriab.ttf'

4
投票

您还可以使用 tkinter ,这比在

C:\Windows\Fonts
中列出字体更好,因为 Windows 也可以在
%userprofile%\AppData\Local\Microsoft\Windows\Fonts

中存储字体

例如,使用列出

tkinter
中可用的字体系列中的以下代码:

from tkinter import Tk, font
root = Tk()
print(font.families())

输出是一个以如下所示开头的元组:

('Arial', 'Arial Baltic', 'Arial CE', 'Cambria', 'Cambria Math'

如果您想获取字体文件名,您可以使用 查找系统字体文件名

来自doc的示例:

from find_system_fonts_filename import AndroidLibraryNotFound, get_system_fonts_filename, FontConfigNotFound, OSNotSupported

try:
    fonts_filename = get_system_fonts_filename()
except (AndroidLibraryNotFound, FontConfigNotFound, OSNotSupported):
    # Deal with the exception
    # OSNotSupported can only happen in Windows, macOS and Android
    #   - Windows Vista SP2 and more are supported
    #   - macOS 10.6 and more are supported
    #   - Android SDK/API 29 and more are supported
    # FontConfigNotFound can only happen on Linux when Fontconfig could't be found.
    # AndroidLibraryNotFound can only happen on Android when the android library could't be found.
    pass

1
投票

上面的答案将列出

/Windows/fonts dir
中的所有字体路径。然而,有些人可能还想获得
the font title, its variations i.e., thin, bold, and font file name etc?
这是代码。

import sys, subprocess

_proc = subprocess.Popen(['powershell.exe', 'Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts"'], stdout=sys.stdout)
_proc.communicate()

现在,对于那些想要字体路径的人来说。这是使用

pathlib
的方法。

import pathlib

fonts_path = pathlib.PurePath(pathlib.Path.home().drive, os.sep, 'Windows', 'Fonts')
total_fonts = list(pathlib.Path(fonts_path).glob('*.fon'))
if not total_fonts:
    print("Fonts not available. Check path?")
    sys.exit()
return total_fonts

1
投票

Windows 注册表显然会跟踪字体:

import winreg

reg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)

key = winreg.OpenKey(reg, r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts',
    0, winreg.KEY_READ)

for i in range(0, winreg.QueryInfoKey(key)[1]):
    print(winreg.EnumValue(key, i))

输出以如下所示的方式开始:

('Arial (TrueType)', 'arial.ttf', 1)
('Arial Bold (TrueType)', 'arialbd.ttf', 1)
('Arial Bold Italic (TrueType)', 'arialbi.ttf', 1)
('Cambria & Cambria Math (TrueType)', 'cambria.ttc', 1)
('Cambria Bold (TrueType)', 'cambriab.ttf', 1)

如果您想要更简单的输出,例如:

Arial (TrueType)

在最后一行使用

print(winreg.EnumValue(key, i)[0])
代替
print(winreg.EnumValue(key, i))

这是由 Mujeeb Ishaque 的响应以及 读取注册表的 Python 代码循环访问值或注册表项组合而成的。_winreg Python

© www.soinside.com 2019 - 2024. All rights reserved.