How to change text of Tkinter button initilised in a loop?

When building GUI applications with Python, you often need to create multiple buttons and update their text dynamically based on user interactions. Tkinter provides an efficient way to create buttons in loops and modify their properties during runtime.

In this article, we'll explore how to initialize buttons in a loop and change their text dynamically when clicked. This technique is essential for creating interactive and responsive GUI applications.

Creating Buttons in a Loop

Instead of creating buttons individually, you can use a loop to generate multiple buttons efficiently. Here's how to create three buttons with sequential labels ?

import tkinter as tk

def create_buttons():
    buttons = []
    
    for i in range(3):
        button = tk.Button(root, text=f"Button {i}")
        button.pack(pady=5)
        buttons.append(button)
    
    return buttons

root = tk.Tk()
root.title("Buttons Created in Loop")
root.geometry("300x200")

buttons_list = create_buttons()

root.mainloop()

This creates three buttons labeled "Button 0", "Button 1", and "Button 2" arranged vertically in the window.

Using Lambda Functions for Dynamic Updates

To make buttons interactive and change their text when clicked, we need to assign command functions. Lambda functions are perfect for this because they allow us to pass specific parameters to the callback function ?

import tkinter as tk

def update_button_text(button):
    current_text = button["text"]
    button.config(text=current_text + " Clicked")

def create_interactive_buttons():
    buttons = []
    
    for i in range(3):
        button = tk.Button(root, text=f"Button {i}")
        button.config(command=lambda b=button: update_button_text(b))
        button.pack(pady=5)
        buttons.append(button)
    
    return buttons

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

buttons_list = create_interactive_buttons()

root.mainloop()

Now each button will append " Clicked" to its text when pressed. The lambda function captures the button reference and passes it to the update function.

Complete Example with Multiple Text Changes

Here's a more comprehensive example that tracks how many times each button has been clicked ?

import tkinter as tk

class ButtonManager:
    def __init__(self, root):
        self.root = root
        self.click_counts = {}
        self.buttons = []
        
    def update_button_text(self, button_id):
        button = self.buttons[button_id]
        self.click_counts[button_id] += 1
        count = self.click_counts[button_id]
        button.config(text=f"Button {button_id} - Clicked {count} times")
    
    def create_buttons(self):
        for i in range(3):
            self.click_counts[i] = 0
            button = tk.Button(
                self.root, 
                text=f"Button {i}",
                command=lambda idx=i: self.update_button_text(idx)
            )
            button.pack(pady=5)
            self.buttons.append(button)

root = tk.Tk()
root.title("Dynamic Button Text Updates")
root.geometry("300x200")

manager = ButtonManager(root)
manager.create_buttons()

root.mainloop()

This example uses a class to manage button states and tracks click counts for each button. Each click updates the button text to show how many times it has been pressed.

Key Points

  • Lambda functions are essential for passing parameters to button commands in loops
  • Button references must be stored to enable dynamic text updates
  • Variable capture in lambda functions prevents late binding issues
  • Class-based approach provides better organization for complex button management

Conclusion

Creating buttons in loops and updating their text dynamically is a powerful technique for building interactive Tkinter applications. Use lambda functions to capture button references and maintain state information for more sophisticated interactions. This approach enables you to create responsive GUIs with minimal code duplication.

---
Updated on: 2026-03-27T16:03:58+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements