Anna
Anna

Reputation: 25

tkinter buttons through a loop, how do i identify which was clicked?

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

Upvotes: 0

Views: 357

Answers (1)

TheLizzard
TheLizzard

Reputation: 7680

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() 

Upvotes: 1

Related Questions