0

I created a loop to create a button for each element in a list. How do I identify which button is clicked and then assign a command to each one, which will create a new page with the same name as the button clicked?.

       yvalue = 200
    for i in sdecks:
        deckbutton1=Button(fcpage,text=i,width=21,bd=2,fg="ghost white",bg="orchid1")
        deckbutton1.place(x=105, y=yvalue)
        yvalue = yvalue + 20
Anna
  • 25
  • 3
  • Does this answer your question? [tkinter creating buttons in for loop passing command arguments](https://stackoverflow.com/questions/10865116/tkinter-creating-buttons-in-for-loop-passing-command-arguments) – TheLizzard Feb 18 '21 at 00:08
  • No because I don't use a lambda in my code. But thanks! – Anna Feb 18 '21 at 00:12
  • 2
    You will need to use `lambda` or `functools.partial` or something similar. Why are you against using `lambda`? – Bryan Oakley Feb 18 '21 at 00:16
  • I'm not against lambda at all, I just have no clue how to use it. – Anna Feb 18 '21 at 00:20
  • To use tkinter buttons effectively you need to know how to use lambda functions. This is a good tutorial: https://www.w3schools.com/python/python_lambda.asp – TheLizzard Feb 18 '21 at 00:21

1 Answers1

1

Either I don't get you question or this (adapted from here) should answer your question:

from functools import partial
import tkinter as tk


def create_new_page(name_of_page):
    print("Creating new page with name=\"%s\"" % name_of_page)


root = tk.Tk()

for i in range(5):
    # Create the command using partial
    command = partial(create_new_page, i)

    button = tk.Button(root, text="Button number"+str(i+1), command=command)
    button.pack()

root.mainloop() 
TheLizzard
  • 7,248
  • 2
  • 11
  • 31