0

I have defined 2 Variables. The first one Works perfectly showing me all the Buttons with the Names of the People in my Global Array players.

I added the command line into my Button which is supposed to Activate my second def Variable once its clicked.The second Variable should save the Buttons Index or Text(tried both) and then i used print, to Display the Things it should save before i can move on.

Now here lies the Problem.

When i click on it , it shows me just an empty Array. I tried to use several other things like [i] instead of text , the btn which was assigned to the Buttons and i tried to Global the btn at one point because i could not use a non Global Variable inside my second function but that also didn't help.I read about partials and Lambda but i cant get my Head around the part that i need to Add/Change to get this going.

Here is my Code:

players=['x','y','z']

players_to_random=[]

def showButtons():
    for i in players:
        btn = Button(window, text=i, command=onclick)
        btn.pack(side=LEFT)

def onclick():
    players_to_random.append() # tried several things with () and without
    print(players_to_random)

showButtons()
tobias_k
  • 81,265
  • 12
  • 120
  • 179
Dimi
  • 13
  • 4
  • On `players_to_random.append()` what was supposed to happen? Because all that is happening is you appending nothing to a list. – Mikael Brenner Feb 15 '19 at 16:17
  • You probably need to add a parameter to `onclick` and use `command=lambda i=i: conclick(i)`. About your next question, see [here](https://stackoverflow.com/questions/19837486/python-lambda-in-a-loop). – tobias_k Feb 15 '19 at 16:20
  • .append() needs an argument if you are going to add anything to your players_to_random list. You can add an argument to onclick() that tracks which button was pressed. for example, onclick(button): players_to_random.append(button). – M Waz Feb 15 '19 at 16:23
  • i had players_to_random.append(text)in there initialy. It was supposed to get the Text from the Buttons. Which means after someone clicked on z Button it was supposed to save the Text from that Button which would be z. So after appending the String Z and other 3 strings ( its supposed to get only 4 but not programmed that far yet),it would randomize the 4 People in the Array and splitting them into 2 Groups. – Dimi Feb 15 '19 at 16:25

1 Answers1

1

Your onclick function has no way to know which button was clicked. You should add a parameter to the function and pass it in the command, using either a lambda (see here) or partial

def showButtons():
    for i in players:
        btn = Button(window, text=i, command=lambda i=i: onclick(i))
        # -- OR THIS (not both) --
        btn = Button(window, text=i, command=functools.partial(onclick, i))
        btn.pack(side=LEFT)

def onclick(player):
    players_to_random.append(player)
    print(players_to_random)
tobias_k
  • 81,265
  • 12
  • 120
  • 179