-1

I want some kind of button so that, when I press it, it will run a function with it's own text, so if the button says "hi there" then when clicked, it'll run someFunction("hi there"). I will be dynamically generating a list of buttons, with different text, based on a list of directories in another folder.

Below is my attempt at it.

import tkinter as tk
for folder in os.listdir("Servers"):
    btns.append(
        tk.Button(
            master,
            text=folder,
            command=lambda: handleButton(<the text of this button>)
        )
    )

Since I'm iterating, I can't just pass folder because it dynamically retrieves it and always uses the last name generated as an arg.

1 Answers1

0

You can use default value of argument on the lambda:

for folder in os.listdir("Servers"):
    btns.append(
        tk.Button(
            master,
            text=folder,
            command=lambda f=folder: handleButton(f)
        )
    )
acw1668
  • 40,144
  • 5
  • 22
  • 34