In this video I’ll show you how to dynamically resize buttons whenever you resize an app Window using Tkinter and Python.

We’ll use the grid system and something called Grid.rowconfigure() and Grid.columnconfigure() to dynamically resize to fit the container that they’re in, and automatically resize themselves if the user manually changes the size of the app.

This is a fun one!

Python Code: button_stretch.py
(Github Code)

from tkinter import *

root = Tk()
root.title('Codemy.com - Expand Buttons To Fit App')
root.iconbitmap('c:/gui/codemy.ico')
root.geometry("500x500")

# Config our column rows and cols
#Grid.rowconfigure(root, index=0, weight=1)
Grid.columnconfigure(root, index=0, weight=1)

# Config row 2
#Grid.rowconfigure(root, 1, weight=1)



# Create two buttons
button_1 = Button(root, text="Button 1")
button_2 = Button(root, text="Button 2")
button_3 = Button(root, text="Button 3")
button_4 = Button(root, text="Button 4")

# Grid them to the screen
button_1.grid(row=0, column=0, sticky="nsew")
button_2.grid(row=1, column=0, sticky="nsew")
button_3.grid(row=2, column=0, sticky="nsew")
button_4.grid(row=3, column=0, sticky="nsew")

# Create list of buttons
button_list = [button_1, button_2, button_3, button_4]

# Define row number
row_number = 0
weight_number = 1
#loop thru the list and config each row automatically
for button in button_list:
	Grid.rowconfigure(root, row_number, weight=weight_number)
	# Increment the counter
	row_number += 1
	weight_number += 1 


root.mainloop()

John Elder

John is the CEO of Codemy.com where he teaches over 100,000 students how to code! He founded one of the Internet's earliest advertising networks and sold it to a publicly company at the height of the first dot com boom. After that he developed the award-winning Submission-Spider search engine submission software that's been used by over 3 million individuals, businesses, and governments in over 42 countries. He's written several Amazon #1 best selling books on coding, and runs a popular Youtube coding channel.

View all posts

Add comment

Your email address will not be published. Required fields are marked *

John Elder

John is the CEO of Codemy.com where he teaches over 100,000 students how to code! He founded one of the Internet's earliest advertising networks and sold it to a publicly company at the height of...