Dynamically Resize Buttons When Resizing a Window using Tkinter


Python has many rich libraries for creating and developing GUI-based applications. Tkinter is one of the most commonly used Python libraries for creating GUI-based applications. It has many features like adding widgets and other necessary attributes necessary for creating an application.

A button is a widget which can be assigned for some particular task or event. However, to dynamically resize or position the button widget, we can configure its position and layout using the Grid module in tkinter. To resize the button dynamically, we can use rowconfiguration() and coloumnconfiguration() methods.

In a tkinter Grid system, there are four attributes which can be used to resize any widget. These attributes generally refer to the direction such as North, South, East, and West. To make the buttons responsive and dynamically resizable according to the screen or window size, we have to use the row and column property in it.

Example

#Importing the tkinter library
from tkinter import *
win= Tk()
win.title("Dynamically Resize Buttons")
win.geometry("700x500")

#Configure Rows and column

Grid.rowconfigure(win, 0,weight=1)
Grid.columnconfigure(win,0,weight=1)
#Create buttons

b1= Button(win, text= "C++")
b2= Button(win, text= "Java")

#Create List of buttons
bl= [b1, b2]

row_no=0
#Loop through all the buttons and configure it row-wise
for button in bl:
   Grid.rowconfigure(win,row_no, weight=1)
   row_no+=1

#Adjust the position in grid and make them sticky

b1.grid(row=0, column=0, sticky= "nsew")
b2.grid(row=1, column=0, stick= "nsew")

win.mainloop()

Output

Running the above code will generate the output and display two buttons horizontally in a row−order, which can be dynamically resizable according to screen or window size.

Updated on: 04-Mar-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements