Why does the calculated width and height in pixel of a string in Tkinter differ between platforms?

You have two problems. Let’s tackle them one at a time

1: the difference between python 2.5 and 2.6 on the same platform with the same font

These two versions of python use different versions of tk. On my mac box, 2.5 uses tk version 8.4.19 and 2.6 uses 8.5.7. In version 8.5.2 of tk were some changes to the font measurement features of tk. Assuming that the changes were improvements, I think it’s safe to assume that the numbers you get from python 2.6 are more accurate than the ones from 2.5.

2: the difference between python 2.6 on the mac and 2.6 on the PC.

Obviously, from the screenshots you include, the PC is using a larger font and thus you get larger numbers for the measurement. The question is, why? You are specifying the font size in points (1/72 of an inch). In order for Tk (or any rendering system) to render the font, it needs to know how many pixels are in an inch on the actual display. This will vary on different systems, and Tk isn’t always given an accurate number by the underlying OS in order to do its calculations.

Historically, Apple and Microsoft have standardized on 72ppi and 96ppi regardless of the actual display, so the numbers are always going to be different. For more information about the differences in how the mac and windows calculate pixel density see the Dots Per Inch article on wikipedia.

You might try solving this by specifying a font in pixels rather than in points. You can do this by using negative numbers for the font size.

Finally, one thing you might add to your little example code is to print out the result of the font.actual() command — you might see something different between your windows and mac boxes, which would explain the differences there. This tells you exactly which font is being used by Tk.

Leave a Comment