How can I find the exact width of a CTkLabel?

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
    # /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 CTkFrames 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:

Closeup around font_size=24:

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?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật