How To Dynamically Resize Button Text in Tkinter?
Last Updated :
16 Oct, 2021
Prerequisite: Python GUI – tkinter, Dynamically Resize Buttons When Resizing a Window using Tkinter
In this article, we will see how to make the button text size dynamic. Dynamic means whenever button size will change, the button text size will also change. In Tkinter there is no in-built function, that will change the button text size dynamically.
Approach:
- Create button and set sticky to all direction
- Set bind, what bind will do, whenever button size change it will call resize function that we will create later.
- Inside the resize function, we will have a different condition, depends on the main window geometry/size.
- Set row and column configure
Let’s understand with step-by-step implementation:
Step 1: Creates a normal Tkinter window.
Python3
from tkinter import *
root = Tk()
root.geometry( "400x400" )
root.mainloop()
|
Output:
Step 2: Create a button inside the main window.
Python3
from tkinter import *
root = Tk()
root.geometry( "400x400" )
button_1 = Button(root , text = "Button 1" )
button_1.grid(row = 0 ,column = 0 )
root.mainloop()
|
Output:
Step 3: Resizing the button text size
Inside the resize function, the “e” value will tell the main window width and height.
Python3
def resize(e):
size = e.width / 10
if e.height < = 400 and e.height > 300 :
button_1.config(font = ( "Helvetica" , 40 ))
elif e.height < 300 and e.height > 200 :
button_1.config(font = ( "Helvetica" , 30 ))
elif e.height < 200 :
button_1.config(font = ( "Helvetica" , 40 ))
|
Below is the full implementation:
Python3
from tkinter import *
root = Tk()
root.geometry( "400x400" )
Grid.columnconfigure(root, index = 0 ,
weight = 1 )
Grid.rowconfigure(root, 0 ,
weight = 1 )
button_1 = Button(root, text = "Button 1" )
button_1.grid(row = 0 ,
column = 0 , sticky = "NSEW" )
def resize(e):
size = e.width / 10
if e.height < = 400 and e.height > 300 :
button_1.config(font = ( "Helvetica" , 40 ))
elif e.height < 300 and e.height > 200 :
button_1.config(font = ( "Helvetica" , 30 ))
elif e.height < 200 :
button_1.config(font = ( "Helvetica" , 40 ))
root.bind( '<Configure>' , resize)
root.mainloop()
|
Output:
Share your thoughts in the comments
Please Login to comment...