Skip to main content
 首页 » 编程设计

python之使用 tkinter 中的 tkFont 来识别字体 (Helvetica-Light) 是否可用/已安装

2025年05月04日15www_RR

我们有一个 Django 应用程序,我们利用 HTML 到 pdf 生成工具来构建 pdf 文档。我们在将 HTML 转换为 pdf 的服务器上不存在字体时遇到了问题,我想添加一个单元测试来验证托管服务器上是否存在字体。

据我所知,我应该使用 Tkinter 的 tkFont 模块来获取可用的字体列表,并确认我们正在使用的字体在此列表中找到。

class VerifyFontsExistOnServer(BaseTransactionTestCase): 
    def test_if_font_exists(self): 
        import Tkinter 
        import tkFont 
        Tkinter.Tk() 
        installed_font_families =[i for i in tkFont.families() 
                                  if 'Helvetica' in i 
                                  or 'Courier' in i 
                                  or 'DejaVuSerif' in i 
                                  or 'OCRA' in i] 
 
        for font in installed_font_families: 
            log.info('{0}'.format(font)) 

但是当我列出项目时,我得到的是 Helvetica 作为字体,但不是 Helvetica-Light。我相信这是该系列的一部分,但有没有办法确定该系列的这种特定字体样式是否存在?

请您参考如下方法:

我最终编写了一个基于 shell 的方法来调用 fc-list 终端命令:

def verify_fonts_are_installed_for_statements(): 
    import subprocess 
    from os import path 
    potential_locations = [ 
        '/usr/bin/fc-list', 
        '/usr/sbin/fc-list', 
        '/usr/local/sbin/fc-list', 
        '/usr/local/bin/fc-list', 
    ] 
    valid_path = None 
    for file_path in potential_locations: 
        if path.exists(file_path): 
            valid_path = file_path 
            break 
    if valid_path is None: 
        raise IOError('could not find fc-list to verify fonts exist.') 
 
    cmd = [valid_path] 
    output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0] 
 
    if 'Helvetica Neue' not in output: 
        raise FontNotInstalledException('Helvetica Neue') 
    if 'Courier' not in output: 
        raise FontNotInstalledException('Courier') 
 
    log.debug('Courier and Helvetica Neue were found to be installed.')