Home > database >  How can I dynamically calculate font size depending on label height in tkinter?
How can I dynamically calculate font size depending on label height in tkinter?

Time:11-04

I'm working on a tkinter script that will display some text and an image below it, but some times the image won't exist. Either way I want the program to dynamically choose the font size based on the max size it could be whilst the text still fitting within the label either in one line or wrapped as long as it fills all the space.

I know I can get the label size by using: self.height = text.winfo_height() but then not sure how I can use this and what the logic would be so I could figure out the right font size to set for the label text. You can see an example of the text in the screenshot but please bare in mind the text could be longer in some situations and sometimes their maybe an image so I need it to be dynamic. Any help would be really appreciated. :) Image

One thing I tried today was doing font size based on the pixel height of the label but that made it too big of course as each letter was the size of the label:

text = Text(
                    self.root)
                text.insert(END, self.text_in_file)
                text.pack(expand=True, fill=BOTH)
                text.update()
                self.height = text.winfo_height()
                self.main_font = TkFont.Font(size = -text.winfo_height())
                text.config(font = self.main_font)
                text.pack(expand=True, fill=BOTH)

CodePudding user response:

If you want to measure the rendered width of a string of text in a specific font you can use the measure method on the font. The height is a property of the font which you can get via the metrics method of the font.

font = Font(...)
width = font.measure("Hello, world")
height = font.metrics()['linespace']

With this information, you use a loop to try different font sizes until you found a size that fit within your button.

  • Related