How To Dynamically Resize Button Text in Tkinter?


Let us suppose we have created a button and a label in Tkinter Frame. The task is to allow the button text to dynamically resize to its main window. We can create the button using a button widget. However, there are several other functions used to create the button label dynamically.

In this example, we will create two buttons with some labels in it. By using the Grid method such as rowconfigure() and columnconfigure(), we will dynamically resize the main window or the root.

To make the button text dynamic, we will use the bind(<Configure>, command) method which will help us to bind the functions and the method together. We can pass a callback function which generally refers to the new location of the widget and a helper function that modifies the changes in the button text according to the window size.

First, we will resize the button text by its width and then by its height.


from tkinter import *

win= Tk()

#Dynamically resize the window and its widget

Grid.rowconfigure(win, index=0, weight=1)
Grid.columnconfigure(win, index=0, weight=1)

#Define the function to change the size of the button text
def resize(e):
   #Get the width of the button
   w= e.width/10
   #Dynamically Resize the Button Text
   b.config(font=("Times New Roman",int(w)))
   #Resize the height
   if e.height <=300:
      b.config(font= ("Times New Roman",30))
   elif e.height<100:
      b.config(font= ("Time New Roman", 10))
#Let us Create buttons,

b.grid(row= 0, column=0, sticky= "nsew")

win.bind('<Configure>', resize)


Running the above code will create a button with the text “Python” and this button can be dynamically resized.

Published on 04-Mar-2021 14:07:52