how to change values ​in buttons done in a loop Tkinter

Question:

how to change values ​​in buttons done in a loop?

I mean a different text, a command for each of the resulting buttons.

the program counts files in a given folder, then this value is passed to the loop that displays the appropriate number of buttons.
here is the sample text:

files = os.listdir(".")
files_len = len(files) - 1
print(files_len)

def add():
    return

for i in range(files_len):
        b = Button(win, text="", command=add).grid()
Asked By: user12608342

||

Answers:

You don’t really need to change the Button‘s text, because you can just put the filename in when they’re created (since you can determine this while doing so).

To change other aspects of an existing Button widget, like its command callback function, you can use the universal config() method on one after it’s created. See Basic Widget Methods.

With code below, doing something like that would require a call similar to this: buttons[i].config(command=new_callback).

To avoid having to change the callback function after a Button is created, you might be able to define its callback function inside the same loop that creates the widget itself.

However it’s also possible to define a single generic callback function outside the creation loop that’s passed an argument that tells it which Button is causing it to be called — which is what the code below (now) does.

from pathlib import Path
import tkinter as tk


win = tk.Tk()

dirpath = Path("./datafiles")  # Change as needed.
buttons = []

def callback(index):
    text = buttons[index].cget("text")
    print(f"buttons[{index}] with text {text!r} clicked")

for entry in dirpath.iterdir():
    if entry.is_file():
        button = tk.Button(win, text=entry.stem,
                           command=lambda index=len(buttons): callback(index))
        button.grid()
        buttons.append(button)

win.mainloop()
Answered By: martineau

Try this. By making a list.

files = os.listdir(".")
files_len = len(files) - 1
print(files_len)

def add():
    return
b=[]
for i in range(files_len):
        b[i] = Button(win, text="", command=add).grid(row=i)
Answered By: Inoejj
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.