I've been using customtkinter for a little while now, and I have a situation where I want to find the exact, pixel-perfect width of a CTkLabel
from the font size and length of the displayed string. However, none of the methods I've tried are accurate. Here's a setup that demonstrates the issue:
import customtkinter as ctk
class MeasuringLabel(ctk.CTkLabel):
def __init__(self, master, font_size=30, length=20, **kwargs):
self.font_size = font_size
self.length = length
self.font = ctk.CTkFont('Courier new', size=self.font_size)
self.text = '0' * self.length # Sample text
super().__init__(master=master, font=self.font, text=self.text,
fg_color='red', **kwargs)
# Measure using ctk.CTkFont.measure
def measured_width(self):
return self.font.measure(self.text, displayof=self)
# Measure one character and extrapolate
def extrapolated_width(self):
return self.font.measure('0', self) * self.length
# Take 0.6*font_size as the width of one character and extrapolate, then round
def theoretical_width(self):
return round(self.font_size * MeasuringLabel.font_width_to_size * self.length)
# Same as above, but round the character width first
def theoretical_round_first_width(self):
return round(self.font_size * MeasuringLabel.font_width_to_size) * self.length
# Get the width of the label using the specified method
def get_width(self, width_method='measured'):
width_function = MeasuringLabel.width_functions[width_method]
return width_function(self)
# Return a CTkFrame with the width as measured using the specified method
def width_bar(self, width_method='measured'):
width = self.get_width(width_method)
print(f'{width_method+": ":<25} {width}')
return ctk.CTkFrame(self.master, width=width, height=10,
corner_radius=0, fg_color='blue')
# This is specific to Courier new. The exact value is 1229/2048 according to
# https://stackoverflow.com/a/19114963/.
font_width_to_size = 0.6
# These functions, when called with a MeasuringLabel instance as the argument,
# return the width as calculated using that method.
width_functions = {
'measured': measured_width,
'extrapolated': extrapolated_width,
'theoretical': theoretical_width,
'theoretical_round_first': theoretical_round_first_width,
'winfo_width': ctk.CTkLabel.winfo_width,
'winfo_reqwidth': ctk.CTkLabel.winfo_reqwidth,
}
class App(ctk.CTk):
def __init__(self, font_size, length):
super().__init__()
self.title('Width measuring')
self.geometry('600x200')
self.label = MeasuringLabel(self, font_size, length)
self.label.grid(row=0, column=0, sticky='w') # Left-align
self.update_idletasks() # Update, so winfo_width returns something useful
for i, width_method in enumerate(MeasuringLabel.width_functions):
new_bar = self.label.width_bar(width_method)
new_bar.grid(row=i+1, column=0, pady=(2,0), sticky='w') # Left-align
app = App(font_size=30, length=20)
app.mainloop()
Essentially, I have 6 different methods in the MeasuringLabel
class (2 of which are inherited from CTkLabel
) for measuring the width. When I initialize the app, it creates a MeasuringLabel
with the specified font_size
and with text = '0' * length
. It then creates 6 CTkFrame
s whose widths come from the different width methods, in the hopes that one will have the same width as the MeasuringLabel
, regardless of font_size and length. However, none of them are accurate:
font_size=30, length=20
:
font_size=37, length=20
:
What is immediately clear is that winfo_width
and winfo_reqwidth
are always too long, and therefore useless. I suspect this might have something to do with screen scaling, so if someone knows how to compensate for this, I'd be very grateful.
Moreover, the first, second, and fourth bars are always equal. This leads me to believe that the CTkFont.measure
method calculates the widths of the characters individually, rounding to ints, and adds them up. I don't understand why this wouldn't give the same width as the MeasuringLabel
though.
In a final effort, I tried to manually set the width of the bar for each font size. I got the following for length=20
:
# The keys are the font_sizes, and the values are the correct widths.
empirical_widths = \
{15: 176, 16: 192, 17: 208, 18: 208, 19: 224,
20: 240, 21: 256, 22: 272, 23: 272, 24: 288,
25: 304, 26: 304, 27: 320, 28: 336, 29: 352,
30: 368, 31: 368, 32: 384, 33: 400, 34: 400,
35: 416}
The worst part is that it isn't even linear. I made this graph to compare the different methods:
Again, measure
, extrapolated
, and theoretical_round_first
overlap (red), and so do winfo_width
and winfo_reqwidth
(gray). And none of them are correct (black) more than occasionally.
I've rubber duck-ed myself. After making the graphs above, I realized that the line for winfo_width
and winfo_reqwidth
had the exact same shape as the empirical line, but scaled differently. It turns out that the scaling factor is precisely the display scaling factor in my device settings, 125%. I found this answer that showed that I can get the scaling factor like this:
import ctypes
scale_factor = ctypes.windll.shcore.GetScaleFactorForDevice(0) / 100
I also noticed that ctk.deactivate_automatic_dpi_awareness()
solves the issue too, and makes all the methods except for theoretical
equal to each other. I'd still like some input on these two solutions, however. Automatic dpi awareness sounds like something I should want, right?