-2

My goal is to add a number of buttons with similar actions but a little difference. So I used a loop to create the buttons and set command to lambda calls to send difference argument.

The code goes like this:

import tkinter as tk

def button_click(*args):
    print(args)

root = tk.Tk()
root.geometry('400x300')

settings=['abc', '123']
for x in settings:
    print(f'Add Button: {x}')
    tk.Button(root, text=x, command=lambda: button_click(x)).pack()

root.mainloop()

With this code, it shows two buttons with difference texts, which is correct. But when click the buttons, button_click() always prints ('123',) no matter which button is clicked.

How can I send 'abc' to button_click() when abc button is clicked, while sending '123' when 123 button is clicked?

Cuteufo
  • 435
  • 4
  • 11

0 Answers0