Python Forum
How can I get the width of a string in Python?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I get the width of a string in Python?
#12
Width with tkinter:

#!/usr/bin/python3
import tkinter
import tkinter.font
app = tkinter.Frame()

def width_and_height_calculator_in_pixel(txt, fontname, fontsize):
    font  = tkinter.font.Font(family=fontname, size=fontsize)
    return (font.measure(txt), font.metrics('linespace'))

print( width_and_height_calculator_in_pixel("Hello World", "Calibri", 11) )
print( width_and_height_calculator_in_pixel("Hello World", "Calibri", 14) )
print( width_and_height_calculator_in_pixel("Hello World", "Calibri", 24) )
print()
print( width_and_height_calculator_in_pixel("Hello World", "Helvetica", 11) )
print( width_and_height_calculator_in_pixel("Hello World", "Helvetica", 14) )
print( width_and_height_calculator_in_pixel("Hello World", "Helvetica", 24) )
Output:
(70, 16) (91, 20) (155, 34) (73, 16) (97, 21) (168, 35)
Reply


Messages In This Thread
RE: How can I get the width of a string in Python? - by heiner55 - May-27-2019, 03:59 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Python code to set column width 1418 11 8,292 Jan-20-2024, 07:20 AM
Last Post: Pedroski55
  Fixed colum width for rowLabels i Matplotlib pandabay 0 1,166 Jun-10-2023, 03:40 PM
Last Post: pandabay
  width of Unicode character Skaperen 6 4,307 Sep-27-2021, 12:41 AM
Last Post: Skaperen
  image.thumbnail(width, height) not working PCesarano 2 5,052 Apr-08-2021, 06:09 PM
Last Post: PCesarano
  fixed width numbers Skaperen 15 12,793 May-27-2019, 09:42 AM
Last Post: Skaperen
  printing text tables with consistent width Skaperen 7 13,256 Jul-01-2018, 02:34 AM
Last Post: Skaperen
  How to measure an inclined beam width and height in image using python? zyb1003 1 4,036 Nov-07-2017, 05:02 AM
Last Post: heiner55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020