pythontkintertk-toolkit

Python/Tkinter: expanding fontsize dynamically to fill frame


I know you can get frame widgets to expand and fill all of the area available to them in their container via these commands: frameName.pack(fill = 'both', expand = True)

What would do the same for a text's font size? Currently my text is an attribute of a label widget. The label widget's parent is frameName.

I guess I could define my own function to call labelName.config(fontsize = N) to update the font size as the frame get's bigger, but I'm not sure how to correlate them.

This is what my program looks like right now: Each of those blocks is a frame widget. I'd like the text to expand to fill up in some capacity the frame, and respond to resizing of the window as well.


Solution

  • You can use tkFont.font

    When you initialize the label set the font to a variable such as:

    self.font = SOME_BASE_FONT
    self.labelName.config(font = self.font)
    

    Then you can use:

    self.font = tkFont.Font(size = PIXEL_HEIGHT)
    

    This you can scale to the height of the label. You can bind a '<Configure>' Event to the widget, and make your callback function adjust the label size.

    frameName.bind('<Configure>', self.resize)
    
    def resize(self, event):
        self.font = tkFont(size = widget_height)
    

    For more info see the documentation here.