How to create Tkinter buttons in a Python for loop?

Tkinter Button widgets are very useful for handling events and performing actions during application execution. We can create Tkinter Buttons using the Button(parent, text, options...) constructor. Using loops, we can efficiently create multiple buttons with minimal code.

Basic Example with For Loop

In this example, we will create multiple buttons using a Python for loop ?

import tkinter as tk
from tkinter import ttk

# Create main window
root = tk.Tk()
root.title("Multiple Buttons Example")
root.geometry("400x300")

# Create buttons using for loop
for i in range(5):
    button = ttk.Button(root, text=f"Button {i}")
    button.pack(pady=5)

root.mainloop()

Creating Buttons with Canvas Layout

Here's an example that creates buttons inside a LabelFrame with Canvas layout ?

import tkinter as tk
from tkinter import ttk

# Create main window
root = tk.Tk()
root.title("Buttons in Canvas")
root.geometry("750x250")

# Create a LabelFrame
labelframe = tk.LabelFrame(root, text="Button Container")

# Define a canvas in the labelframe
canvas = tk.Canvas(labelframe)
canvas.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)

labelframe.pack(fill=tk.BOTH, expand=True, padx=30, pady=30)

# Create Button widgets in Canvas using loop
for i in range(5):
    button = ttk.Button(canvas, text=f"Button {i}")
    button.pack(pady=2)

root.mainloop()

Creating Buttons with Grid Layout

For better control over button positioning, you can use grid layout ?

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.title("Grid Layout Buttons")
root.geometry("300x200")

# Create buttons in a 2x3 grid
for row in range(2):
    for col in range(3):
        button_num = row * 3 + col + 1
        button = ttk.Button(root, text=f"Button {button_num}")
        button.grid(row=row, column=col, padx=5, pady=5)

root.mainloop()

Adding Functionality to Loop-Created Buttons

You can add click handlers to buttons created in loops ?

import tkinter as tk
from tkinter import ttk

def button_click(button_num):
    print(f"Button {button_num} was clicked!")

root = tk.Tk()
root.title("Interactive Buttons")
root.geometry("300x250")

# Create buttons with command functionality
for i in range(4):
    button = ttk.Button(
        root, 
        text=f"Click Me {i}",
        command=lambda x=i: button_click(x)
    )
    button.pack(pady=5)

root.mainloop()

Storing Button References

To modify buttons later, store them in a list ?

import tkinter as tk
from tkinter import ttk

# Create button list demonstration
buttons = []
button_texts = ["Start", "Pause", "Stop", "Reset"]

# Simulate creating buttons and storing references
for i, text in enumerate(button_texts):
    button_info = {"text": text, "id": i}
    buttons.append(button_info)
    print(f"Created button: {button_info}")

# Simulate accessing stored buttons
print(f"\nFirst button: {buttons[0]}")
print(f"Total buttons: {len(buttons)}")
Created button: {'text': 'Start', 'id': 0}
Created button: {'text': 'Pause', 'id': 1}
Created button: {'text': 'Stop', 'id': 2}
Created button: {'text': 'Reset', 'id': 3}

First button: {'text': 'Start', 'id': 0}
Total buttons: 4

Key Points

  • Use for loops to create multiple buttons efficiently
  • Store button references in lists if you need to modify them later
  • Use lambda functions carefully in loops to avoid variable binding issues
  • Choose appropriate layout managers: pack(), grid(), or place()

Conclusion

Creating Tkinter buttons in loops is an efficient way to generate multiple similar widgets. Use grid layout for precise positioning and store button references when you need to modify them later.

Updated on: 2026-03-25T19:38:45+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements