-1

I have a problem with my tkinter code. That's what I got so far:

from tkinter import *

root = Tk()



def create_button():
        liste = [['Name 1', 'Name 2', 'Name 3'], ['Name 4', 'Name 5', 'Name 6']]

        #giving any button a diffrent command by changing the 'group'-parameter from the function show_player
        for i in range(len(liste)):
            Button_name = 'Group ' + str(i+1)
            Button(root, text = Button_name, bg = 'white', command= lambda:[show_player(liste, i)]).pack()

def show_player(list1, group):

    for name in list1[group]:
        Label(root, text = name).pack() 

create_button()

root.mainloop()

Regradless of which button I'm pressing, I get the names "Name 4", "Name 5", "Name 6",

but I expected the first button to create the labels with the names "Name 1", "Name 2", "Name 3"

Does anyone know why it doesn't work?

1 Answers1

1

It doesn't work because i will take its last value, 1, for all lambdas you created since function body is not executed until you call it. You can pass i as a parameter to lambda to solve this problem:

command=lambda i=i:[show_player(liste, i)]

Or you can use partial:

from functools import partial
...

command=partial(show_player, liste, i)
Asocia
  • 5,935
  • 2
  • 21
  • 46