在Python中测量字符串宽度

时间:2017-09-10 10:37:38

标签: python string width

我有一些字体(Times New Roman,14),我需要测量字符串宽度。我在API中找到了matplotlib和示例:

from matplotlib import rcParams
import os.path
afm_filename = os.path.join(rcParams['datapath'], 'fonts', 'afm', 
               'ptmr8a.afm')
from matplotlib.afm import AFM
afm = AFM(open(afm_filename))
afm.string_width_height('What the heck?')

但是我无法理解我应该粘贴什么而不是#34; datapaths"," fonts"," afm"。 这是在Python中获取sting宽度的方法吗?也许另一种方式?

1 个答案:

答案 0 :(得分:1)

import tkinter as Tkinter 
from tkinter import font as tkFont

Tkinter.Frame().destroy()
txt = tkFont.Font(family="Times New Roman", size=14)
width = txt.measure("What the heck?")
print(width)