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


When we build computer programs, making them look good and easy to use is super important. Tkinter, a handy Python tool, helps us create these user-friendly Graphical User Interfaces (GUIs). Now, imagine you have some buttons in your program, and you want to change what they say when someone clicks on them. That's where Tkinter's dynamic text updates come into play, especially when you create buttons in a loop.

In this article, we'll take a closer look at how to make our Tkinter buttons update their text in a cool way. We'll cover the basics of creating buttons in a loop and learn how to change their text dynamically. These skills will come in handy when you want to make your programs more interactive and user-friendly. Let's dive in!

How To Initialize Buttons in a Loop?

Imagine you need several buttons in your program, and you don't want to create them one by one. That's where loops come in handy. In the following example, we're using a loop to make three buttons, each labeled "Button 0," "Button 1," and "Button 2" −

import tkinter as tk
# Function to create buttons
def Init_buttons():
   # List to store button instances
   buttons = []

   # Loop to create three buttons
   for i in range(3):
      # Create a button with the text "Button 0," "Button 1," etc.
      button = tk.Button(root, text=f"Button {i}")

      # Pack the button into the Tkinter window
      button.pack()

      # Add the button instance to the list
      buttons.append(button)

   # Return the list of button instances
   return buttons

# Create the main Tkinter window
root = tk.Tk()
# Set the window title
root.title("Change Text of Tkinter Button Initialised in Loop")  
# Set window dimensions
root.geometry("720x250")

# Call the create_buttons function to create and display buttons
buttons_list = Init_buttons()

# Start the Tkinter event loop
root.mainloop()

Here, Init_buttons is a function that uses a loop to create and show these buttons in a Tkinter window. It's like a shortcut to avoid writing the same code for each button individually.

Dynamic Text Updates

Dynamic text updates become necessary when the text on buttons needs to change based on user interactions or other events. This article focuses on a scenario where buttons need to be updated dynamically when clicked.

Lambda Functions for Button Commands

To achieve dynamic updates, lambda functions are often used with button commands. Lambda functions allow us to pass parameters to functions. In this case, we want to pass the button instance to the update_text function when the button is clicked. The following modification to the code achieves this −

# Function to create and configure buttons
def Init_buttons():
   # List to store button instances
   buttons = []

   # Loop to create three buttons
   for i in range(3):
      # Create a button with the text "Button 0," "Button 1," etc.
      # Set the command to call update_text function with the corresponding button as an argument
      button = tk.Button(root, text=f"Button {i}", command=lambda idx=i: update_text(buttons[idx]))
       
      # Pack the button into the Tkinter window
      button.pack()

      # Add the button instance to the list
      buttons.append(button)

   # Return the list of button instances
   return buttons

Updating Button Text Dynamically

The update_text function is responsible for dynamically updating the button text. It appends " Clicked" to the current text of the button −

# Function to update the text of a button dynamically
def update_text(button):
   # Get the current text of the button and append " Clicked"
   new_text = button["text"] + " Clicked"
    
   # Configure the button to display the updated text
   button.config(text=new_text)

Example

The complete example demonstrates the integration of these concepts.

import tkinter as tk
# Function to update the text of a button dynamically
def update_text(button):
   # Get the current text of the button and append " Clicked"
   new_text = button["text"] + " Clicked"
    
   # Configure the button to display the updated text
   button.config(text=new_text)

# Function to create and configure buttons
def Init_buttons():
   # List to store button instances
   buttons = []

   # Loop to create three buttons
   for i in range(3):
      # Create a button with the text "Button 0," "Button 1," etc.
      # Set the command to call update_text function with the corresponding button as an argument
      button = tk.Button(root, text=f"Button {i}", command=lambda idx=i: update_text(buttons[idx]))
      
      # Pack the button into the Tkinter window
      button.pack()

      # Add the button instance to the list
      buttons.append(button)

   # Return the list of button instances
   return buttons

# Create the main Tkinter window
root = tk.Tk()
# Set the window title
root.title("Change Text of Tkinter Button Initialised in Loop")  
# Set window dimensions
root.geometry("720x250")

# Call the create_buttons function to create and display buttons
buttons_list = Init_buttons()

# Start the Tkinter event loop
root.mainloop()

In the below outputs, you can see the buttons are created in a loop, and their text is updated dynamically when clicked.

Output

Conclusion

In conclusion, mastering dynamic text updates for Tkinter buttons initialized in a loop is key to creating interactive and user-friendly Python GUI applications. By understanding the basics of Tkinter and leveraging lambda functions, we can efficiently manage button instances and respond to user interactions. The provided examples demonstrate the creation of dynamic buttons and showcase how to update their text seamlessly. Applying these techniques enhances the overall user experience, making applications more engaging and responsive.

Updated on: 05-Dec-2023

78 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements