0

I have some font (Times New Roman, 14) and I need to measure string width. I found matplotlib and example from API:

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?')

But I can't understand what I should paste instead of "datapaths", "fonts", "afm". Is it the way to get sting width in Python? Maybe another way?

5
  • string width? do you mean the length of a string? Commented Sep 10, 2017 at 10:44
  • The question is, where is your file located? Commented Sep 10, 2017 at 10:48
  • Do you mean get string length in pixels? Commented Sep 10, 2017 at 10:56
  • 1
    My problem is to orginize some text in Word. So, I use python-docx for reading docx document. And I need to measure string width in cm in the document. If I use default settings (in code above): Commented Sep 10, 2017 at 11:06
  • Error: if not line.startswith(b'StartFontMetrics'): TypeError: startswith first arg must be str or a tuple of str, not bytes Commented Sep 10, 2017 at 11:07

1 Answer 1

3
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)
Sign up to request clarification or add additional context in comments.

8 Comments

Some error: File "E:/=ПРОЕКТЫ=/=PYTHON=/=ТЕКСТ=/Calc_String_Variants/Calc.py", line 4, in <module> txt = tkFont.Font(family="Times New Roman", size=14) File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\tkinter\font.py", line 93, in init tk.call("font", "create", self.name, *font) AttributeError: 'NoneType' object has no attribute 'call'
it is some add:
Updated once more. Should work for python 2 and 3. What do you mean "it is some add" ?
I add string "tkinter.Frame().destroy()" in Python 3 version and it is work, but it has problem: Width of my Word document is 505 mm. So if I add all letters "a" (230 letters) for full string - the answer is 1840, but if I add all letters "c" (230 letters) for full string - the answer is 2070. It is great difference, but in Word is about the same.
Updated with destroy()
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.