pythonstringuser-interfacetkinterwidth

Get PythonTkinter width of string in pixels using given font


Given a string such as "this is a string" or "THIS IS A STRING" and knowing the font family and size, how can the pixel width be calculated?

This is required to align columns for an eyesome GUI.


Solution

  • There is a method measure() of Font object to give the width in pixels of a string:

    import tkinter as tk
    from tkinter.font import Font
    
    root = tk.Tk()
    font = Font(family='Arial', size=20)
    
    for s in ('this is a string', 'THIS IS A STRING'):
        w = font.measure(s)
        print(f'Width of "{s}" is {w} pixels')
    

    Output:

    Width of "this is a string" is 169 pixels
    Width of "THIS IS A STRING" is 231 pixels
    

    Document on measure().