Python/Tkinter: expanding fontsize dynamically to fill frame

强颜欢笑 提交于 2019-12-01 13:08:46
user3727843

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.

I've been trying to figure out how to get the text to automatically resize in tkinter.

The key to getting it working for me was to assign the calculated height to the size in the custom font object. Like so: self.label_font['size'] = height

Full example:

from tkinter import font
import tkinter as tk


class SimpleGUIExample:
    def __init__(self, master):
        self.master = master
        self.master.title("A simple Label")
        self.master.bind('<Configure>', self.resize)

        self.label_font = font.Font(self.master, family='Arial', size=12, weight='bold')

        self.label = tk.Label(self.master, text="Simple Label Resizing!")
        self.label.config(font=self.label_font)
        self.label.pack(fill=tk.BOTH, expand=tk.YES)

        self.close_button = tk.Button(self.master, text="Close", command=master.quit)
        self.close_button.pack()

    def resize(self, event):
        height = self.label.winfo_height()
        width = self.label.winfo_width()
        height = height // 2
        print('height %s' % height)
        print('width %s' % width)
        if height < 10 or width < 200:
            height = 10
        elif width < 400 and height > 20:
            height = 20
        elif width < 600 and height > 30:
            height = 30
        else:
            height = 40
        print('height %s' % height)

        self.label_font['size'] = height
        print(self.label_font.actual())


root = tk.Tk()
simple_gui = SimpleGUIExample(root)
root.mainloop()
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!