How to change the text of a specific button in Python

Question:

I’m using tkinter and this problem bothers me a lot.
My goal:

  1. Create several buttons
  2. When clicking a specific button, change the text shown on that button

I tried the codes below, but no matter what button I clicked, only the last one got changed.

import tkinter as tk

list1 = []

def update_btn_text(index):
   list1[index].set('new')
   
for i in range(10):
   btn_text = tk.StringVar()
   list1.append(btn_text)
   btn = tk.Button(root, textvariable=list1[i], command=lambda: update_btn_text(i))
   btn_text.set('button' + str(i+1))
   btn.pack()

root.mainloop()

I guess the problem is because of the i value, but how can I fix it?
Thanks a lot!

Asked By: zhmff

||

Answers:

You have to create a local variable for every iteration and pass it as a value in updatd_btn_text()

command=lambda i=i: update_btn_text(i)

Also you could try this for configuring text of the button

def update_btn_text(index,button):
   button.config(text=list1[index])
   
for i in range(10):
   btn = tk.Button(root)
   btn.pack()
   btn.config (command=lambda i=i, btn=btn: update_btn_text(i, btn))
Answered By: user15801675
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.