0
win=Tk()
level1=matrixmaker(4)

def display(x,y): 
if z["text"] == " ":
    # switch to Goodbye
    z["text"] = level1[x][y]
else:
    # reset to Hi
    z["text"] = " "


for x in range(0,4):
    for y in range(0,4):
        z=Button(win,text=" ", command=display(x,y))
        z.grid(row=x,column=y)

I have this code but I don't know how to get the display function to work. How can I call the button and change the text without it having a hardcoded variable name?

Wayne Werner
  • 49,299
  • 29
  • 200
  • 290
Laura
  • 53
  • 5
  • In Tkinter, the `command` argument is a _reference_ to a function, not the function itself. You have to make the argument into `command=display` with no arguments. See here: http://stackoverflow.com/questions/6920302/how-to-pass-arguments-to-a-button-command-in-tkinter – Colby Gallup Dec 01 '15 at 23:30
  • Also, you're calling a three argument function with only two arguments (that can't be added anyway). – Colby Gallup Dec 01 '15 at 23:32
  • use `command=lambda a=x,b=y:display(a,b)` – furas Dec 01 '15 at 23:38
  • i added the lambda but now whenever i click anything on the grid it only changes the bottom right button – Laura Dec 01 '15 at 23:38
  • because you change `z` - but `z` is the last button created in `for` loop. – furas Dec 01 '15 at 23:39

1 Answers1

4

You can't assign the command to the button with the called function (display(x, y)) because this assigned what this function returns (None) to the button's command. You need to assign the callable (display) instead.

To do this and pass arguments you'll need to use a lambda:

z = Button(win, text='')
z['command'] = lambda x=x, y=y, z=z: display(x, y, z)
z.grid(row=x, column=y)

Also, you'll want to change your display() function to accept another argument z so that the correct button gets changed (and correct the indentation):

def display(x,y,z): 
    if z["text"] == " ":
        # switch to Goodbye
        z["text"] = level1[x][y]
    else:
        # reset to Hi
        z["text"] = " "
MrAlexBailey
  • 5,219
  • 19
  • 30