Search code examples
pythonfontstkinterttk

Why is tkfont.Font().measure returning large values?


I've been developing a Python 3.X app which leverages tkinter, specifically using ttk.Treeview in order to build some tables from a database. When measuring how wide to make the columns, it seems that the value returned is often too large.

Where val is the value of the cell, the following code is used to find the width:

col_w = tkfont.Font().measure(str(val).rstrip())

Here's what the end result is in practice:

Actual result

Here's what I would like to see:

Desired result

Any thoughts?


Solution

  • First, make sure you're getting the width of the correct font from your Treeview.

    The following give me two different values:

    Python 3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 20:20:57) [MSC v.1600 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import tkinter as tk
    >>> from tkinter import font
    >>> root = tk.Tk()
    >>> print(font.Font().measure('foo'))
    22
    >>> print(font.nametofont('TkHeadingFont').measure('foo'))
    18
    

    Next, check the stretch setting for your columns, as it will affect column widths.

    Also, you may want to pad the string length a little bit to give the elements some breathing room. I add two spaces to the string, plus account for my standard X padding in layouts:

    # Defined elsewhere in my module
    PAD_X = 5
    
    def get_padded_text_width(standard_font, text):
       return font.nametofont(standard_font).measure(text + '__') + (2 * PAD_X)