1

I need to create multiple buttons with different names (each new name is equal to the name of the previous button + the iterating value at that moment.) Please help me out, here is my code.

buttons = [0]*len(gg.allStudents)

for j in range(len(gg.allStudents)):
    buttons[j] = tk.Button(wind, text=gg.allStudents[j].name, height = 2, width = 20, command=lambda: plotMarks(j))
    buttons[j].pack()

The looping conditions that I have used our correct. The only help I need is to find a way to store each new button with a new name into the 'buttons' list.

BlazeRod11
  • 23
  • 6
  • The buttons don't need names. You can reference them via the `buttons` array. Why do you think they need names? – Bryan Oakley Aug 26 '20 at 18:22
  • What I intend to do is, when the user clicks on any button, a corresponding plot should pop up. Since I didn't name the buttons, the same 'button' gets overwritten in each 'for' loop, and so, even if I click the first button, I get the graph corresponding to the last button. – BlazeRod11 Aug 26 '20 at 19:50
  • The solution to that problem isn't giving it a name, it's in properly creating the button command. See https://stackoverflow.com/q/17677649/7432. You can use `lambda j=j: plotMarks(j)` – Bryan Oakley Aug 26 '20 at 20:12

1 Answers1

0

Your issue is not what you think it is. It can be easily solved by changing:

command=lambda: plotMarks(j) to command=lambda j=j: plotMarks(j).

The reason this works is because, in your version, you are sticking the variable j in all of your commands, and they will all use whatever the final value of j is. In the second version you are sticking the current value of j in your command.

To understand this better all we have to do is expand the lambdas.

def add2(n):
    return n+2    

#equivalent of your current version    
j = 6
def currentLambdaEquivalent():
    global j
    print(add2(j)) 

currentLambdaEquivalent() #8


#equivalent of second version
def alternateLambdaEquivalent(j):
    print(add2(j))
    
alternateLambdaEquivalent(2) #4
OneMadGypsy
  • 4,640
  • 3
  • 10
  • 26